简体   繁体   中英

How to Set click listener on marker in google map?

i have two marker in example where one is for current location and one is for destination i have drawn a Route path between them but now in same example i want to set a click listener on both the marker can you suggest some good example related this..?

Here is how to do it using Kotlin:

private lateinit var mMap: GoogleMap  //declaration inside class

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
    mMap.setOnMarkerClickListener { marker ->
        if (marker.isInfoWindowShown) {
            marker.hideInfoWindow()
            } else {
            marker.showInfoWindow()
            }
        true
        }
}

Hope this helps some beginner like me.

This is how you would go about adding an onClick listener for markers on a map:

GoogleMap mMap;
Marker marker = mMap.addMarker(
   new MarkerOptions()
       .position(new LatLng(dLat, dLong))
       .title("Your title")                                       
       .icon(BitmapDescriptorFactory.fromResource(R.drawable.map_pin)));

mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    @Override
    public boolean onMarkerClick(Marker m) {}
}
  1. Let your class/fragment implement OnMarkerClickListener
  2. Register marker click callback to your googleMap with googleMap.setOnMarkerClickListener(this); in your setup
  3. Override the onMarkerClick

     @Override public boolean onMarkerClick(final Marker marker) { //handle click here }

On newer versions of Google Maps, this is no longer valid, you should use:

MarkerManager(mMap).newCollection().apply {
    addMarker(MarkerOptions()
        .position(it)
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)))

        setOnMarkerClickListener {
            //handleClick    
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM