简体   繁体   中英

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

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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM