0

How can I get the nearest point from my location in a polyline? I have used the below code to do my job

click here to view code

but it gives me output something like this:

List<LatLng> points = new ArrayList<>();
points.add(new LatLng(2, 2));
points.add(new LatLng(4, 2));
points.add(new LatLng(4, 4));
points.add(new LatLng(2, 4));
points.add(new LatLng(2, 2));

LatLng testPoint = new LatLng(3, 0);

LatLng nearestPoint = findNearestPoint(testPoint, points);
Log.e("NEAREST POINT: ", "" + nearestPoint); // lat/lng: (3.0,2.0)

But I want the index of the polyline (ArrayList containing a list of Polyline) which is closest to the given point, I have tried many methods but none of them worked out.

Please let me know if you got the solution.

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
Adarsh
  • 45
  • 8
  • That function `findNearestPoint` is finding a point _somewhere_ on the line segments specified in the list closest to the specified point - it is not necessarily finding the closest vertex (or the points in your list).. –  Nov 07 '18 at 17:10
  • Take a look at https://stackoverflow.com/questions/36104809/find-the-closest-point-on-polygon-to-user-location/36105498#36105498 – antonio Nov 07 '18 at 20:06
  • @antonio Hi, I used your code to get the closest polyline index of the given point but as Andy said it is finding a point somewhere in the line segment. So, How can I get the index of polyline list ? – Adarsh Nov 09 '18 at 03:57
  • @Adarsh Don't use that function - just loop on your `points`, use `SphericalUtil.computeDistanceBetween` and find the minimum distance and that is your point/index. For long lists you'll have to consider optimization. –  Nov 10 '18 at 15:20
  • @Andy ok thanks for your answer anyhow I have used this code https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/PolyUtil.java to get the index and it's working perfectly – Adarsh Nov 11 '18 at 07:13

0 Answers0