Reputation: 3123
I have a GoogleMap in my Flutter app. When the page loads it calls on API and gets a list of geolocations which I use to create a list of markers.
My GoogleMap uses this list of markers and they display nicely, however, I would like one of them to be active. I can't see anything in the API documentation that says this is possible. How can I achieve this?
Upvotes: 8
Views: 4936
Reputation: 29
Use GoogleMapController to set the marker active, allMarkers here is a list of markers which might be coming from the database and the first one (index 0) will be active after execution of:
_googleMapController.showMarkerInfoWindow(allMarkers[0].markerId);
Upvotes: 3
Reputation: 2447
There are ongoing issues in flutter related to the same thing here and here.
Currently, It is not possible to do this via official maps SDK.
However, thanks to the community there is another forked project which has an implementation which can help you achieve this. Checkout this.
Upvotes: 2
Reputation: 20158
You can implement custom active state through onTap
event handler.
In stateful widget create state to track selected marker and rebuild all markers comparing their IDs to the highlighted one:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class GoogleMapsLabPage extends StatefulWidget {
@override
State<GoogleMapsLabPage> createState() => GoogleMapsLabPageState();
}
class GoogleMapsLabPageState extends State<GoogleMapsLabPage> {
final preset = [
{"id": "mountain-view", "lat": 37.421512, "lng": -122.084101},
{"id": "san-bruno", "lat": 37.62816, "lng": -122.426491},
{"id": "san-francisco", "lat": 37.789972, "lng": -122.390013},
{"id": "sunnyvale", "lat": 37.403694, "lng": -122.031583}
];
String _selectedOffice = '';
List<Marker> _buildMarkers() {
return preset.map((office) {
return Marker(
markerId: MarkerId(office['id']),
position: LatLng(office['lat'], office['lng']),
icon: office['id'] == _selectedOffice
? BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueBlue)
: BitmapDescriptor.defaultMarker,
consumeTapEvents: true,
onTap: () {
setState(() {
_selectedOffice = office['id'];
});
});
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(37.7, -122.2), zoom: 9.0),
markers: _buildMarkers().toSet(),
),
);
}
}
By setting consumeTapEvents
parameter to true
we can disable default tap handling by centering the map on the marker and displaying its info window.
Upvotes: 2
Reputation: 88
mapController.addMarker(
MarkerOptions(
position: LatLng(your values here),
),
);
Upvotes: 0