How to detect a click on a polyline

我只是一个虾纸丫 提交于 2019-11-27 15:04:30

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!

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);
eanix

The solution above doesn't work correctly. Especially if we have large distance between two points of polyline.

I answered this question: Clickable Polylines Google Maps API Android

We can modify code above like this:

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng clickCoords) {
        for (PolylineOptions polyline : mPolylines) {
            if (PolyUtil.isLocationOnPath(clickCoords, polyline.getPoints(), true, 100)) {
                // user clicked on polyline
            }
        }
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!