Shahryar Rafique
Shahryar Rafique

Reputation: 1358

Display multiple markers on Google maps in flutter

I am able to show a single marker in the google maps but when I am trying to add the list of markers only the first marker show in a flutter. Kindly guide me on how to add a list of markers in google maps. Here is my code.

class MapsScreen extends StatefulWidget {
  static const routeName = '/maps-screen';

  @override
  _MapsScreenState createState() => _MapsScreenState();
}

class _MapsScreenState extends State<MapsScreen> {
  Completer<GoogleMapController> _controller = Completer();
  Set<Marker> _markers = {};
  Marker marker1 = Marker(
    markerId: MarkerId('Marker1'),
    position: LatLng(32.195476, 74.2023563),
    infoWindow: InfoWindow(title: 'Business 1'),
    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
  );
  Marker marker2 = Marker(
    markerId: MarkerId('Marker2'),
    position: LatLng(31.110484, 72.384598),
    infoWindow: InfoWindow(title: 'Business 2'),
    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
  );
  List<Marker> list = [];
  @override
  void initState() {
    list = [marker1, marker2];
    // _markers.addAll(list);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Maps'),
      ),
      body: GoogleMap(
        markers: Set<Marker>.of(list),
        onMapCreated: (GoogleMapController controller) {
          _controller.complete(controller);
        },
        initialCameraPosition: CameraPosition(
          target: LatLng(32.1749132, 74.1779387),
          zoom: 11.0,
        ),
      ),
    );
  }
}

Upvotes: 1

Views: 7432

Answers (1)

Aamil Silawat
Aamil Silawat

Reputation: 8229

You can do this way

List<Marker> list = [
 Marker(
    markerId: MarkerId('Marker1'),
    position: LatLng(32.195476, 74.2023563),
    infoWindow: InfoWindow(title: 'Business 1'),
    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed),
  );
   Marker(
    markerId: MarkerId('Marker2'),
    position: LatLng(31.110484, 72.384598),
    infoWindow: InfoWindow(title: 'Business 2'),
    icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue),
  );
 ];

And use setState when you adding data in list

       setState(() {
           markers.addAll(list);
          });

Upvotes: 5

Related Questions