Dilshan Madulanka
Dilshan Madulanka

Reputation: 25

How to add multiple markers on the google map

I am trying add multiple markers from the coordinates read from the firebase. It reads all the coordinates and store in the list. I have created the addMarker function to add the markers to the map. But it only prints a one marker, the last marker coordinates read. Can anyone help me to resolve this as I am new to flutter.

import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:async';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final textcontroller = TextEditingController();
  final databaseRef = FirebaseDatabase.instance.reference();
  Completer<GoogleMapController> _controller = Completer();
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  double latitude = 0;
  double longitude = 0;
  var myList = [];
  List<LatLng> list = [];

  void initState() {
    super.initState();
    setState(() {
      firebaseRead();
    });
  }

  void firebaseRead() {
    databaseRef.child('Locations').onValue.listen((Event event) {
      myList = event.snapshot.value;

      setState(() {
        for (int x = 0; x < myList.length; x++) {
          double latitude = myList[x]['lat'];
          double longitude = myList[x]['long'];
          LatLng location = new LatLng(latitude, longitude);
          if (list.contains(location)) {
            list.clear();
            list.add(location);
          } else {
            list.add(location);
          }

          addMarker(list[x]);
        }
      });

    });
    //print(list);
  }

  void addMarker(loc) {
    final MarkerId markerId = MarkerId('Marker 1');

    final Marker marker = Marker(
      markerId: markerId,
      position: LatLng(loc.latitude, loc.longitude),
      infoWindow: InfoWindow(title: 'test'),
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
      //print(marker);
    });
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Demo"),
      ),
      body: GoogleMap(
        mapType: MapType.normal,
        markers: Set.of(markers.values),
        initialCameraPosition:
            CameraPosition(target: LatLng(6.9271, 79.8612), zoom: 15),
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () {
          firebaseRead();
        },
        label: const Text('Refresh'),
        icon: const Icon(Icons.refresh),
        backgroundColor: Colors.blueAccent,
      ),
    );
  }
}

Upvotes: 1

Views: 2031

Answers (2)

Lalit Fauzdar
Lalit Fauzdar

Reputation: 6363

You're always using a single markerId which means you're overwriting the previous marker with the next marker and which is why there's always only one.

For dynamic marker's list, you've to pass a dynamic markerId. See, the modified code below:

void firebaseRead() {
    databaseRef.child('Locations').onValue.listen((Event event) {
        myList = event.snapshot.value;
        setState(() {
            for (int x = 0; x < myList.length; x++) {
              double latitude = myList[x]['lat'];
              double longitude = myList[x]['long'];
              LatLng location = new LatLng(latitude, longitude);
              if (list.contains(location)) {
                 list.clear();
                  list.add(location);
              } else {
                  list.add(location);
              }

              //Passing a dynamic marker id as the index here.
              addMarker(list[x], x);
            }
        });
    });
    //print(list);
}

//Adding Index here as an argument
void addMarker(loc, index) {
    //Making this markerId dynamic
    final MarkerId markerId = MarkerId('Marker $index');

    final Marker marker = Marker(
       markerId: markerId,
       position: LatLng(loc.latitude, loc.longitude),
       infoWindow: InfoWindow(title: 'test'),
    );

    setState(() {
      // adding a new marker to map
      markers[markerId] = marker;
      //print(marker);
    });
}

In this code, the change is index is taken from the for loop and passed to the markerId, so now, the markerId will be different for each marker passed from the firebaseRead().

Upvotes: 1

Aamil Silawat
Aamil Silawat

Reputation: 8229

I am using google_maps_flutter: ^0.5.30 this version You can do something like this:-

List<Marker> _markers = <Marker>[];

for(var track in myList){
        if(track["latitude"] != "" && track["latitude"] != "null"){
          _markers.add(Marker(markerId: MarkerId(myList.indexOf(track).toString()),
              position: LatLng(double.parse(track["latitude"]), double.parse(track["longitude"])),
              infoWindow: InfoWindow(title: track["Name"])));
        }
      }
      
      
      GoogleMap(
          initialCameraPosition: CameraPosition(
              target: latitude == null && longitude == null
                  ? LatLng(23.022505, 72.571365)
                  : LatLng(latitude, longitude)),
          mapType: MapType.normal,
          markers: Set<Marker>.of(_markers),
          onMapCreated: _onMapCreated,
          myLocationEnabled: true,
        )

Upvotes: 1

Related Questions