How to detect a click on a polyline

shehzy picture shehzy · Aug 8, 2014 · Viewed 12.7k times · Source

If there is a polyline on googlemap and a click is performed on the map, then how can I check whether that click was on polyline or somewhere else?

Polyline line = googleMap.addPolyline(new PolylineOptions()
       .add(new LatLng(51.2, 0.1), new LatLng(51.7, 0.3))
       .width(5)
       .color(Color.RED));

googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {          

    }
});

Answer

sigute picture sigute · Jan 14, 2016

The most recent Google Maps API now includes polylines click listener. You need to be using 8.4+. In gradle file:

compile 'com.google.android.gms:play-services-maps:8.4.0

Setup map polyline listener:

googleMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() 
{
    @Override
    public void onPolylineClick(Polyline polyline)
    {
        //do something with polyline
    }
});

Polyline needs to be clickable for the listener to work.

PolylineOptions line = new PolylineOptions();
//add path points, set colour, etc. here
Polyline polyline = googleMap.addPolyline(line);
polyline.setClickable(true);