Search code examples
androidgoogle-mapspolyline

How to detect a click on a polyline


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() {          

    }
});

Solution

  • Unfortunately there's no such thing as a polyline click listener so you'll have to listen to clicks on map and check if a click was registered on any of your polylines. You'll also have to save references to the polylines you added to your map.

    Here's an example that calculates if there's a polyline ~100meters away from the click.

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng clickCoords) {
            for (PolylineOptions polyline : mPolylines) {
                for (LatLng polyCoords : polyline.getPoints()) {
                    float[] results = new float[1];
                    Location.distanceBetween(clickCoords.latitude, clickCoords.longitude,
                            polyCoords.latitude, polyCoords.longitude, results);
    
                    if (results[0] < 100) {
                        // If distance is less than 100 meters, this is your polyline
                        Log.e(TAG, "Found @ "+clickCoords.latitude+" "+clickCoords.longitude);
                    }
                }
            }
        }
    });
    

    Once a polyline is found you can save that distance as float minDistance; and then loop through other polylines to check if there is a closer one.

    To make this more precise you can get the zoom level at each touch and multiply your required distance. Like 100 * (22 - mMap.getCameraPosition().zoom) (you need to use bigger distance at lower zoom levels).

    Good luck!