'How to calculate the distance between GeoPoint and Polyline
Suppose i have:
GeoPoint p = new GeoPoint(10.08, 11.09); //(lat, long)
and a Polyline (a sequence of Geopoints)
ArrayList<GeoPoint> waypoints = new ArrayList<>()
waypoints.add(new GeoPoint(20.90, 20.80);
waypoints.add(new GeoPoint(30.90, 30.80);
...
...
How can i calculate the distance between p and the Polyline? I'm using Osmodroid https://github.com/osmdroid/osmdroid
Solution 1:[1]
After further improving my former post... this is good enough to not need an package method :) ;) good night
the GeoPoint is from the osmdroid package
public class MyGeoTool{
public double distanceToPolylineAsDouble(List<GeoPoint> polyline, GeoPoint actual_point) {
GeoPoint final_nearest_point;
Double approximation_to_line = null;
for (int i = 0; i < polyline.size() - 1; i++) {
GeoPoint nearest_point = closestPointOnLine(polyline.get(i), polyline.get(i+1), actual_point);
Double approximation_here = nearest_point.distanceToAsDouble(actual_point);
if ((approximation_to_line == null) || (approximation_here < approximation_to_line)) {
approximation_to_line = approximation_here;
final_nearest_point = nearest_point;
}
}
return approximation_to_line;
}
private GeoPoint closestPointOnLine(GeoPoint a, GeoPoint b, GeoPoint p) {
Vector a_to_p = new Vector(a, p);
Vector a_to_b = new Vector(a, b);
double square_magnitude = Math.pow(a_to_b.x, 2) + Math.pow(a_to_b.y, 2);
double atp_dot_atb = a_to_p.x * a_to_b.x + a_to_p.y * a_to_b.y;
double t = clamp(atp_dot_atb / square_magnitude, 0d, 1d);
return new GeoPoint(a.getLatitude() + a_to_b.x * t, a.getLongitude() + a_to_b.y * t);
}
}
class Vector {
GeoPoint a;
GeoPoint b;
public double x;
public double y;
protected Vector(GeoPoint a, GeoPoint b) {
this.a = a;
this.b = b;
this.x = this.X();
this.y = this.Y();
}
protected double X() {
return this.b.getLatitude() - this.a.getLatitude();
}
protected double Y() {
return this.b.getLongitude() - this.a.getLongitude();
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |