How can I calculate a current distance to polyline points on google maps v2 in android?

后端 未结 1 879
眼角桃花
眼角桃花 2021-01-23 22:50

I have used tutorial from the link below to display Google map route in Android app. My question is how can I calculate distance to polyline points on map? Like when I use Googl

1条回答
  •  一整个雨季
    2021-01-23 23:26

    I use this method for Markers. Assuming you have Latitude and Longitude of the points that make up the Polyline this should do:

    public class MapUtils {
    
    public static float distBetween(LatLng pos1, LatLng pos2) {
        return distBetween(pos1.latitude, pos1.longitude, pos2.latitude,
                pos2.longitude);
    }
    
    /** distance in meters **/
    public static float distBetween(double lat1, double lng1, double lat2, double lng2) {
        double earthRadius = 3958.75;
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
                + Math.cos(Math.toRadians(lat1))
                * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
                * Math.sin(dLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double dist = earthRadius * c;
    
        int meterConversion = 1609;
    
        return (float) (dist * meterConversion);
    }
    }
    

    To determine wether the road is turning, I would look into euclidean angle between vectors (x being current location and y being a polyline point)

    Simply take your current location and a LatLng from some distance ahead for this.

    Calculation is based on: http://en.wikipedia.org/wiki/Euclidean_space#Angle

    Location currentLocation; // obtained somewhere in your code
    LatLng polylinePoint; // a point further ahead
    
    double cLat = currentLocation.getLatitude();
    double cLon = currentLocation.getLongitude();
    
    double pLat = polylinePoint.latitude;
    double pLon = polylinePoint.longitude;
    
    double angle = Math.acos(
            (cLat*pLat+cLon+pLon) / norm(cLat,cLon)*norm(pLat,cLon));
    
    private double norm(double x, double y) {
        return Math.sqrt(Math.pow(x, 2)*Math.pow(y, 2));    
    }
    

    This is untested so might contain error.

    0 讨论(0)
提交回复
热议问题