Flutter – Drag marker and get new position

dartfluttergeolocationgoogle maps

In Flutter I have a map that take the device position with help of location. Then i use this position to show marker in Google map with help of Google Maps Flutter plugin.

The code is similar to

 child: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: CameraPosition(
          target: LatLng(lat, lng),
          zoom: 5,
        ),
        markers: Set<Marker>.of(
          <Marker>[
            Marker(
              draggable: true,
              markerId: MarkerId("1"),
              position: LatLng(lat, lng),
              icon: BitmapDescriptor.defaultMarker,
              infoWindow: const InfoWindow(
                title: 'Usted está aquí',
              ),
            )
          ],
        ),
        onMapCreated: (GoogleMapController controller) {
          mapController = controller;
        },
      ))

If location plugin fails or take wrong data i need to have the option to reposition this marker. I use draggable: true to drag marker, but i need to take the new latitude and longitude for save it in database.

So the question is: Using the draggable how can i get the new latitude and longitude?

Best Answer

If you allow me, I would suggest a different approach to this problem. I think in the current version of google maps for Flutter (0.4.0) you don't have a method to get the new position after dragging the marker, so my solution was to use the camera position to move the marker around and then use the current camera position to get the new coordinates. So in your code, you could do something like this:

    child: GoogleMap(
        mapType: MapType.hybrid,
        initialCameraPosition: CameraPosition(
          target: LatLng(lat, lng),
          zoom: 5,
        ),
        markers: Set<Marker>.of(
          <Marker>[
            Marker(
              draggable: true,
              markerId: MarkerId("1"),
              position: LatLng(lat, lng),
              icon: BitmapDescriptor.defaultMarker,
              infoWindow: const InfoWindow(
                title: 'Usted está aquí',
              ),
            )
          ],
        ),
        onCameraMove: ((_position) => _updatePosition(_position)),            
        onMapCreated: (GoogleMapController controller) {
          mapController = controller;
        },
      ))

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["1"];

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

I hope it helps!

Related Topic