fluttermapsmarkergoogle-maps-flutter

How to add multiple markers inside google maps of flutter


I am trying to add more than one marker in my google maps screen.. but I didn't get any idea how to do that.. I have applied some examples in some articles.. but I get an error...here is part of my code..

GoogleMap(
              initialCameraPosition: const CameraPosition(
                target: LatLng(...,...),
                zoom: 18.0,
              ),
              markers: Set.of([marker]), // here I want to add multiple markers
              onMapCreated: _onMapCreated,
)

is there a simple way to add multiple markers?

and here is the code for marker

void loc(LocationData a) {
    LatLng latlng = LatLng(a.latitude, a.longitude);
    this.setState(() {
      marker = Marker(
        markerId: MarkerId("mine"),
        position: latlng,
        icon: BitmapDescriptor.defaultMarker,
        draggable: false,
        zIndex: 1,
      );
    });
  }

Solution

  • google_maps_flutter has provided example for adding multiple markers: place marker, you should check this out:

      void _add() {
        final int markerCount = markers.length;
    
        if (markerCount == 12) {
          return;
        }
    
        final String markerIdVal = 'marker_id_$_markerIdCounter';
        _markerIdCounter++;
        final MarkerId markerId = MarkerId(markerIdVal);
    
        final Marker marker = Marker(
          markerId: markerId,
          position: LatLng(
            center.latitude + sin(_markerIdCounter * pi / 6.0) / 20.0,
            center.longitude + cos(_markerIdCounter * pi / 6.0) / 20.0,
          ),
          infoWindow: InfoWindow(title: markerIdVal, snippet: '*'),
          onTap: () {
            _onMarkerTapped(markerId);
          },
          onDragEnd: (LatLng position) {
            _onMarkerDragEnd(markerId, position);
          },
        );
    
        setState(() {
          markers[markerId] = marker;
        });
      }
    

    UPDATED:

    GoogleMap(
                  onMapCreated: _onMapCreated,
                  initialCameraPosition: const CameraPosition(
                    target: LatLng(-33.852, 151.211),
                    zoom: 11.0,
                  ),
                  // TODO(iskakaushik): Remove this when collection literals makes it to stable.
                  // https://github.com/flutter/flutter/issues/28312
                  // ignore: prefer_collection_literals
                  markers: Set<Marker>.of(markers.values),
                ),
    
    void loc(LocationData a) {
        LatLng latlng = LatLng(a.latitude, a.longitude);
         final Marker marker = Marker(
            markerId: MarkerId("mine"),
            position: latlng,
            icon: BitmapDescriptor.defaultMarker,
            draggable: false,
            zIndex: 1,
          );
        setState(() {
          markers[markerId] = marker;
        });
      }