Google Maps for Flutter - Get new position of mark

2019-06-10 13:55发布

问题:

I want to create a location picker in flutter using google Google Maps for Flutter and it's marker. It's possible to create a dragable marker by creating a marker with dragable option set to true. Using the following code segment.

Widget _buildMap(BuildContext context) {
  return GoogleMap(
    options: GoogleMapOptions(
      cameraPosition: CameraPosition(
        target: LatLng(7.2906, 80.6337),
        zoom: 7.0,
      ),
      compassEnabled: true,
    ),
    onMapCreated: (controller) {
      _mapController = controller;
      controller.addMarker(
        MarkerOptions(
          draggable: true,
          flat: false,
          position: LatLng(7.2906, 80.6337),
        ),
      );
    },
  );
}

But I can't find a way to get the new location of the marker after dragging the marker. I tried to get the new location of the marker by referring to markers attribute of the MapController but it returns the initial location of the marker.

_mapController.markers.forEach((marker) {
  print("Pos: " + marker.options.position.toString())
});

// Prints "Pos: LatLng[7.2906, 80.63369999999998]"

What am I doing wrong here or is there another way to accomplish this use case? Thank you.

回答1:

That package is a developers preview, version 0.0.3. Don't consider it for production work until it hits 1.0. In the meanwhile, you might file a issue to inform the flutter team of your specific priorities.



回答2:

My approach to this problem was to use the camera position to move the marker around and then use the current camera position to get the new coordinates. You'll need to refactor a little bit your code to use the latest changes present in version 0.4 of google maps for flutter, which include this callback that you will need to add to your code:

onCameraMove: ((_position) => _updateMarker(_position)),                        

Then you can set your marker's new state each time the user moves the camera around and use this coordinates for any other purpose you need:

void _updatePosition(CameraPosition _position) {
    Position newMarkerPosition = Position(
        latitude: _position.target.latitude,
        longitude: _position.target.longitude);
    Marker marker = markers["your_marker"];

    setState(() {
      markers["your_marker"] = marker.copyWith(
          positionParam: LatLng(newMarkerPosition.latitude, newMarkerPosition.longitude));
    });
  }

Tell me if it works!



回答3:

I managed this by adding listener and few conditions

  mapController.addListener(() async {
      final cameraCoordinates = mapController.cameraPosition.target;
      if (!mapController.isCameraMoving &&
          widget.selectedPlace.options.position !=
              mapController.cameraPosition.target) {
        mapController.updateMarker(
            widget.selectedPlace, MarkerOptions(position: cameraCoordinates));
      }
    });

Here mapController is GoogleMapController instance.