how to get lat lng of position click on polyline?

2019-07-23 08:18发布

问题:

I am getting setOnPolylineClickListener by following method.

mMap.setOnPolylineClickListener(new GoogleMap.OnPolylineClickListener() {
            @Override
            public void onPolylineClick(Polyline polyline) {
}

But this returns whole PolylineI want Latitude and Longitudeof click position like we get by MapClickListener how to achieve this ?

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(final LatLng point) {

        }); 

I have tried using PolyUtil with following code it also doesn't work.

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(final LatLng point) {
                if (PolyUtil.isLocationOnPath(point, finalPolylines.getPoints(), true)) {
                    // user clicked on polyline

                    Toast.makeText(getContext(), "found", Toast.LENGTH_SHORT).show();
                    Log.d("found", "onMapClick:  found");
                }
            }
        });

回答1:

You are doing everything alright:

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

    @Override
    public void onMapClick(final LatLng point) {
        if (PolyUtil.isLocationOnPath(point, finalPolylines.getPoints(), true)) {
            // user clicked on polyline

            Toast.makeText(getContext(), "found", Toast.LENGTH_SHORT).show();
            Log.d("found", "onMapClick:  found");
        }
    }
});

is the solution, but PolyUtil.isLocationOnPath(LatLng point, java.util.List<LatLng> polyline, boolean geodesic) has 0.1 meter tolerance by default, and touch just didn't on path with this precise. Use PolyUtil.isLocationOnPath(LatLng point, java.util.List<LatLng> polyline, boolean geodesic, double tolerance) instead, set appropriate tolerance (10 meters, or 20 meters - or even more, it depends on zoom level)

mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

    @Override
    public void onMapClick(final LatLng point) {
        if (PolyUtil.isLocationOnPath(point, finalPolylines.getPoints(), true, 20)) {
            // user clicked on polyline

            Toast.makeText(getContext(), "found", Toast.LENGTH_SHORT).show();
            Log.d("found", "onMapClick:  found");
        }
    }
});

and everything should works!

UPDATE:

Also you can modify tolerance depending on zoom level, like:

...
switch (mMap.getCameraPosition().zoom) {
    ...
    case 16:
        tolerance = 30;
    break;
    case 15:
        tolerance = 45;
    break;
    ...
}
...

or use formula: tolerance = f(zoom level) like tolerance = 1000 / mMap.getCameraPosition().zoom;.