Flutter/Dart Add custom Tap Events for Google Maps Marker
Keep in mind that the current release is a developer preview at version 0.0.3. Give it a bit of time to get things working, please!
void _onMapCreated(GoogleMapController controller){
this._controller = controller;
controller.onMarkerTapped.add(_onMarkerTapped);
}
void _onMarkerTapped(Marker marker) {
...
}
Widget build(BuildContext context) {
... GoogleMap(
onMapCreated: _onMapCreated,
options: GoogleMapOptions(
...
));
}
You can use onTap or onLongPress option in the map plugin to monitor tap events. Then you can add the marker in following way on the tapped position
final Set<Marker> _markers = {};
GoogleMap(onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 13.0,
),
compassEnabled: true,
tiltGesturesEnabled: false,
onTap: (latlang){
if(_markers.length>=1)
{
_markers.clear();
}
_onAddMarkerButtonPressed(latlang);
},
myLocationEnabled: true,
myLocationButtonEnabled: true,
mapType: mapType,
markers: _markers,
onCameraMove: _onCameraMove,
),
where the _onAddMarkerButtonPressed function is
void _onAddMarkerButtonPressed(LatLng latlang) {
loadAddress(latlang);
_latLng = latlang;
setState(() {
_markers.add(Marker(
// This marker id can be anything that uniquely identifies each marker.
markerId: MarkerId(_lastMapPosition.toString()),
position: latlang,
infoWindow: InfoWindow(
title: address,
// snippet: '5 Star Rating',
),
icon: BitmapDescriptor.defaultMarker,
));
});
}
With the release of version ^0.3.0+1 a new Marker API was introduced which handles markers as widgets (including an onTap() method). This way a Google Map has a markers:
option which admits a list of Marker objects. Each of the elements can be defined like this:
Marker(
markerId: MarkerId("id"), // a string for marker unique id
icon: BitmapDescriptor.defaultMarker(), // options for hues and custom imgs
position: LatLng(lat, long), // lat and long doubles
onTap: () {
//this is what you're looking for!
}
),
Much easier than the former controller approach!