Reputation: 1476
I'm using Flutter to make a mobile application that uses a map. We decided to use Google map and the plugin for flutter we use is:
google_maps_flutter: ^0.5.7
I understand that adding markers to the map works like this:
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
Marker _marker = new Marker(
icon: BitmapDescriptor.defaultMarker,
markerId: _markerId,
position: LatLng(34.024441,-5.0310968),
infoWindow: InfoWindow(title: "userMarker", snippet: '*'),
);
GoogleMap _map;
@override
void initState(
markers[_markerId] = _marker;
_map = new GoogleMap(
/* other properties irrelevant to this prob */
markers: Set<Marker>.of(_markers.values),
);
);
The above snippet does work, I get to see the marker on the map. But modifying the marker or trying to add another marker like in the snippet below does not work.
FloatingActionButton(
onPressed: () {
setState(() {
_marker = new Marker(
icon: BitmapDescriptor.defaultMarker,
markerId: _markerId,
position: LatLng(currentLocation.latitude, currentLocation.longitude),
infoWindow: InfoWindow(title: "userMarker", snippet: '*'),
onTap: () {
debugPrint("Marker Tapped");
},
);
markers[_markerId] = _marker; // What I do here is modify the only marker in the Map.
});
markers.forEach((id,marker) { // This is used to see if the marker properties did change, and they did.
debugPrint("MarkerId: $id");
debugPrint("Marker: [${marker.position.latitude},${marker.position.longitude}]");
});
});
)
My intention here is using another plugin (geoLocator) to get location data of the user and change the only marker I have so it can track his movements. The debugPrint shows that the data is indeed changing, but I see no change in the map (the initial marker that I change uses a different location than my own when I test).
Upvotes: 13
Views: 25142
Reputation: 5345
If there's no specific reason for you to use Map data structure, here's what I've done in the past.
I have a Set
of Marker
in my State
Set<Marker> markers = Set();
Give it to the map widget. markers: markers
GoogleMap(
onMapCreated: _onMapCreated,
myLocationEnabled: true,
initialCameraPosition:
CameraPosition(target: LatLng(0.0, 0.0)),
markers: markers,
)
And then adding the Marker, which I'm building with search result and which you'll be building with your user's location, to Set of Marker in setState method.
// Create a new marker
Marker resultMarker = Marker(
markerId: MarkerId(responseResult.name),
infoWindow: InfoWindow(
title: "${responseResult.name}",
snippet: "${responseResult.types?.first}"),
position: LatLng(responseResult.geometry.location.lat,
responseResult.geometry.location.lng),
);
// Add it to Set
markers.add(resultMarker);
Edit: I've just noticed you're using GoogleMap widget in your initState
, you need to move it to the build
method if you want to rebuild it everytime with the new state values.
Upvotes: 21