How to drag and drop a marker in Flutter Maps?
Using Flutter Maps, you can easily implement drag and drop functionality for markers on a map.
Step 1: Add the Syncfusion® Flutter Maps package in your pubspec.yaml file and initialize the Maps with necessary properties.
late List<MapLatLng> mapMarkers; late MapTileLayerController mapController; @override void initState() { mapController = MapTileLayerController(); mapMarkers = <MapLatLng>[ MapLatLng(13.239945, 19.391806), // Africa MapLatLng(28.7041, 77.1025) // India ]; super.initState(); }
Step 2: Return any widget that will be a child of gesture detector in the MapMarker using the markerBuilder callback.
Step 3: Convert the obtained global position into a local position using the markers render box in the gesture detectors onPanUpdate callback, then find the new latlng value for that point using the MapTileLayerController.pixelToLatLng() method.
Step 4: Update the current marker latitude and longitude values and pass its index in the MapTileLayerController.updateMarkers() method.
The following example explains how to drag and drop the markers in Maps.
@override Widget build(BuildContext context) { return Scaffold( body: SfMaps( layers: [ MapTileLayer( urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png', controller: mapController, initialMarkersCount: mapMarkers.length, markerBuilder: (BuildContext context, int index) { return MapMarker( longitude: mapMarkers[index].longitude, latitude: mapMarkers[index].latitude, child: GestureDetector( onPanUpdate: (DragUpdateDetails details) { final RenderBox markerRenderBox = context.findRenderObject()! as RenderBox; // To obtain the maps local point, we have converted the global // point into local point using the marker render box. After that // we have converted that point into latlng and updated it’s // position. final MapLatLng latLng = mapController.pixelToLatLng( markerRenderBox.globalToLocal(details.globalPosition)); mapMarkers[index] = MapLatLng(latLng.latitude, latLng.longitude); mapController.updateMarkers([index]); }, child: Icon( Icons.location_on, color: Colors.red, size: 30, ), ), ); }, ), ], ), ); }
Output
Check the following links for more features in Syncfusion® Flutter Maps:
Live samples
Blogs related to Maps
- Introduction to Flutter Maps
- Add live location tracking to your app using Flutter Maps
- Easily Visualize OpenStreetMaps and Bing Maps in Flutter
- Display routes and highlight regions in Flutter Maps
- Add animated and interactive custom Map markers in Flutter Maps