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

2,214

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

Share:
2,214
kokserek
Author by

kokserek

Updated on December 28, 2022

Comments

  • kokserek
    kokserek over 1 year

    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.

    • SardorbekR
      SardorbekR about 3 years
      you want to get road directions between two points or you want a straight line between two points?
    • kokserek
      kokserek about 3 years
      I want a straight line. Finally, I want to let users build an arbitrary polygone and find markers inside.
  • SardorbekR
    SardorbekR about 3 years
    yes, List<Marker> markers = []; I updated answer
  • kokserek
    kokserek about 3 years
    Yes, the (1) works! Fantastic! I go ahead. My task is to build a polygon / polyline and let users look at markers inside of it, as I wrote here: stackoverflow.com/questions/66374167/…
  • SardorbekR
    SardorbekR about 3 years
    @kokserek I have no idea what to do with it yet/