Add a marker dynamically by clicking on the map

Hello,


I am interested in using syncfusion_flutter_map in one of our projects. For this, it is essential that I can add a marker on the map by clicking on it and retrieve the latitude and longitude of the point. I am using Openstreetmap, is there a solution?

Thank you in advance for your help



3 Replies 1 reply marked as answer

LR Lakshmi Radha Krishnan Syncfusion Team June 25, 2021 02:17 PM UTC

Hi,


Greetings from Syncfusion support. 



You can place the marker at the tapped position using the MapTileLayerController.pixelToLatLng method. We have attached code snippet for your reference, kindly let us know if you need further assistance with this.


Code snippet:


class _MarkerPageState extends State<MarkerPage> {
 
late MapLatLng _markerPosition;   late _CustomZoomPanBehavior _mapZoomPanBehavior;   late MapTileLayerController _controller;
 
@override   void initState() {     _controller = MapTileLayerController();     _mapZoomPanBehavior = _CustomZoomPanBehavior()..onTap = updateMarkerChange;     super.initState();   }
 
void updateMarkerChange(Offset position) {     _markerPosition = _controller.pixelToLatLng(position);     if (_controller.markersCount > 0) {       _controller.clearMarkers();     }     _controller.insertMarker(0);   }
 
@override   Widget build(BuildContext context) {     return Scaffold(       appBar: AppBar(title: Text('Marker sample')),       body: SfMaps(         layers: [           MapTileLayer(             urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',             zoomPanBehavior: _mapZoomPanBehavior,             controller: _controller,             markerBuilder: (BuildContext context, int index) {               return MapMarker(                 latitude: _markerPosition.latitude,                 longitude: _markerPosition.longitude,                 child: Icon(Icons.add_location, color: Colors.red),               );             },           ),         ],       ),     );   } }

class _CustomZoomPanBehavior extends MapZoomPanBehavior {   late MapTapCallback onTap;
 
@override   void handleEvent(PointerEvent event) {     if (event is PointerUpEvent) {       onTap(event.localPosition);     }     super.handleEvent(event);   } }

typedef MapTapCallback = void Function(Offset position);


Regards, 

Lakshmi R. 



Marked as answer

NC Nathan Cortat July 6, 2021 03:01 PM UTC

Hello,


Thank you very much Lakshmi,

I successfully get the position of a click on the map !


Have a nice day !



PG Pon Geetha A J Syncfusion Team July 7, 2021 09:49 AM UTC

Hi Nathan, 
  
We are glad to know that your issues is resolved. 
  
Regards, 
Geetha 


Loader.
Up arrow icon