Search code examples
flutteropenstreetmapmarker

In Flutter, how to add a marker on openstreetmap by tapping a screen or clicking a button?


It should be very simple, but I can't seem to find how to do it.

In Flutter / openstreetmap, I need to: (1) put a marker on the map by tapping a map and/or clicking a button; (2) connect two of these markers with a line(s).

Any ideas would be appreciated.


Solution

  • 1) For adding markers:

    List<Marker> markers = [];
    

    Inside Build method:

              FlutterMap(
                mapController: _mapController,
                options: MapOptions(
                    center: LatLng(41.238250, 69.342939),
                    zoom: 9.6,
                    onTap: (latlng) {
                      setState(() {
                        markers.add(
                          Marker(
                            width: 150.0,
                            height: 150.0,
                            point: latlng,
                            builder: (ctx) => const Icon(
                              Icons.location_on,
                              color: Colors.red,
                              size: 35.0,
                            ),
                          ),
                        );
                      });
                    }),
                layers: [
                  MarkerLayerOptions(
                    markers: [
                      for (int i = 0; i < markers.length; i++) markers[i]
                    ],
                  ),
                ],
              ),
    

    2) If you want to get directions between two points, you can use this service, it's free. http://project-osrm.org

    The link I am using for getting directions between two points.

    https://api.openrouteservice.org/v2/directions/driving-car?api_key=$OSRM_API_KEY&start=${origin.longitude},${origin.latitude}&end=${destination.longitude},${destination.latitude}

    It takes, API Key and starting point lat-long and ending point lat-long.

    Response gives you multiple lat-long points, and if you give these points to polyLine parameter of map, it will draw you a road line between two points

    Let me know if you need any clarification on some part of my answer