How to add a marker tap/click on map using Flutter

2020-03-26 05:22发布

问题:

I just started to take a look into flutter/dart. Coming from HTML5/Javascript, I wonder what would be an equivalent to:

google.maps.event.addListener(map, 'click', function(event) {
 placeMarker(event.latLng);
});

function placeMarker(location) {
var marker = new google.maps.Marker({
    position: location, 
    map: map
});

}

I've looked all around the internet, and I found many examples of adding markers, but not on map click.(e.g. Example 1, Example 2). The google_maps_flutter plugin doesn't mention anything about this yet. Is it possible to add the marker by tapping the map, or is this something that's still not available?

Thanks in advance.

回答1:

The plugin has finally added an onTap property for the GoogleMap Class.

final ArgumentCallback<LatLng> onTap

Example:

GoogleMap(
    markers: _markers,
    initialCameraPosition: _theSecretLocation,
    onMapCreated: (GoogleMapController controller) {
      _controller.complete(controller);
    },
    onTap: _handleTap,
  ),
  ...

 _handleTap(LatLng point) {
setState(() {
  _markers.add(Marker(
    markerId: MarkerId(point.toString()),
    position: point,
    infoWindow: InfoWindow(
      title: 'I am a marker',
    ),
    icon:
        BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueMagenta),
  ));
});
}


回答2:

you want to take the mapcontroller and use it for ex:

**GoogleMapController controller;**

**controller.onMarkerTapped.add((Marker marker){/...your code.../);**


回答3:

It's same with my problem. you have to pull google_map branch, that provide listener like onMapClickListener etc. maybe this can help you: https://github.com/flutter/plugins/pull/1121

Regards