Home > Software design >  How to add multiple markers in Google map with Flutter Web?
How to add multiple markers in Google map with Flutter Web?

Time:08-04

How can I add multiple markers by tap/click the map in Google map with Flutter Web? All of the tutorial were using google_maps_flutter not google_maps_flutter_web.

CodePudding user response:

try this,

//list of markers 
final Set<Marker> markers = new Set();

markers.add(Marker( //add first marker
  markerId: MarkerId(showLocation.toString()),
  position: showLocation, //position of marker
  infoWindow: InfoWindow( //popup info 
    title: 'My Custom Title ',
    snippet: 'My Custom Subtitle',
  ),
  icon: BitmapDescriptor.defaultMarker, //Icon for Marker
));

markers.add(Marker( //add second marker
  markerId: MarkerId(showLocation.toString()),
  position: LatLng(27.7099116, 85.3132343), //position of marker
  infoWindow: InfoWindow( //popup info 
    title: 'My Custom Title ',
    snippet: 'My Custom Subtitle',
  ),
  icon: BitmapDescriptor.defaultMarker, //Icon for Marker
)); 

GoogleMap( //Map widget from google_maps_flutter package
  markers: markers, //markers to show on map
)

CodePudding user response:

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'src/locations.dart' as locations;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final Map<String, Marker> _markers = {};
  Future<void> _onMapCreated(GoogleMapController controller) async {
    final googleOffices = await locations.getGoogleOffices();
    setState(() {
      _markers.clear();
      for (final office in googleOffices.offices) {
        final marker = Marker(
          markerId: MarkerId(office.name),
          position: LatLng(office.lat, office.lng),
          infoWindow: InfoWindow(
            title: office.name,
            snippet: office.address,
          ),
        );
        _markers[office.name] = marker;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Google Office Locations'),
          backgroundColor: Colors.green[700],
        ),
        body: GoogleMap(
          onMapCreated: _onMapCreated,
          initialCameraPosition: const CameraPosition(
            target: LatLng(0, 0),
            zoom: 2,
          ),
          markers: _markers.values.toSet(),
        ),
      ),
    );
  }
}
  • Related