How to use BitmapDescriptor.fromAssetImage() to set a custom Marker icon?
Define a field in Class:
BitmapDescriptor myIcon;
Retrieve icon before the Map is ready.
@override
void initState() {
BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(48, 48)), 'assets/my_icon.png')
.then((onValue) {
myIcon = onValue;
});
}
set the Icon:
icon: myIcon;
Make sure you have set the icon in Flutter section of pubspec.yaml
assets:
- assets/my_icon.png
A better solution will be to wrap the GoogleMap widget inside a FutureBuilder. Generate your markers in a separate Future, and assign the result of the future to the markers in the GoogleMap widget
FutureBuilder:
FutureBuilder(
future: generateMarkers(positions),
initialData: Set.of(<Marker>[]),
builder: (context, snapshot) => GoogleMap(
initialCameraPosition: CameraPosition(target: LatLng(0, 0)),
markers: snapshot.data,
),
);
markers generator:
Future<Set<Marker>> generateMarkers(List<LatLng> positions) async {
List<Marker> markers = <Marker>[];
for (final location in positions) {
final icon = await BitmapDescriptor.fromAssetImage(
ImageConfiguration(size: Size(24, 24)), 'assets/my_icon.png');
final marker = Marker(
markerId: MarkerId(location.toString()),
position: LatLng(location.latitude, location.longitude),
icon: icon,
);
markers.add(marker);
}
return markers.toSet();
}