Reputation: 99
I have a simple Flutter app with GoogleMap. All I want to do is, when a button is clicked, all markers in my array are displayed on the map.
note - I am able to gather and store all places related information from Google API and it is ready to be used. Data is not the problem. The only problem is displaying markers from my array.
I have 2 sets of code, (1) GoogleMap integration and (2) Code for creating marker and pushing each marker to my array.
(1)
Container(
child: GoogleMap(
markers: Set<Marker>.from(multipleMarkers),
polylines: polylines,
trafficEnabled: false,
rotateGesturesEnabled: true,
buildingsEnabled: true,
myLocationEnabled: true,
myLocationButtonEnabled: false,
mapType: MapType.normal,
zoomControlsEnabled: false,
initialCameraPosition: CameraPosition(target:currentLatLng, zoom: 15),
onMapCreated: (GoogleMapController controller) {
_controller.complete(controller);
setPolylines();
},
),
),
(2) This method is linked to a button.
addMultipleMarkers(LatLng latLng) {
//this method finds the total number of Lat-Lngs in the array -> 20 Lat-Lngs exist
print("'addMultipleMarkers()' ====================> ${nearbySearchResult.length}");
for (var i in nearbySearchResult){
double? lat = 0;
double? lng = 0;
if (i.geometry!.location!.lat != null){
lat = i.geometry!.location!.lat;
}
if (i.geometry!.location!.lng != null){
lng = i.geometry!.location!.lng;
}
//creating marker, adding info, and pushing it to 'multitpleMarkers' array
Marker marker = Marker(
markerId: MarkerId(i.geometry!.location.toString()),
position: LatLng(lat!, lng!),
infoWindow: InfoWindow(
title: 'Origin',
snippet: "originSnippet"
),
icon: BitmapDescriptor.defaultMarker,
);
//I tried to setState each time marker is added in array - not working
setState(() {
multipleMarkers.add(marker);
});
}
//this print line confirms that 20 marks have have been successfully stored in 'multipleMarkers' array
print("============> TOTAL MARKERS " + multipleMarkers.length.toString());
}
Upvotes: 0
Views: 1309
Reputation: 1084
Maybe use a boolean to use your set or an empty set :
markers: _isMarkersShowed ? Set<Marker>.from(multipleMarkers) : {}, // not sure if {} is an empty Set, if it doesn't work try with [].
And the code to show/hide your markers (call this function when you tap the button):
showHideMarkers(){
setState(()=> _isMarkersShowed = !_isMarkersShowed);
}
Upvotes: 1