我希望得到两个纬度和经度之间的距离

时间:2018-05-01 10:25:04

标签: android

我想得到两个即将到来的纬度和经度之间的确切差异。为了实现这一点,我尝试了很多代码。像:

GeodeticCalculator geoCalc = new GeodeticCalculator();
Ellipsoid reference = Ellipsoid.WGS84;
Double dbLat = Double.valueOf(latLong[0]);
Double dbLong = Double.valueOf(latLong[1]);
Toast.makeText(this, "" + dbLat + "," + dbLong, Toast.LENGTH_SHORT).show();
GlobalPosition pointA = new GlobalPosition(Double.valueOf(latLong[0]), Double.valueOf(latLong[1]), 0.0);
GlobalPosition userPos = new GlobalPosition(lat2, long2, 0.0);
distance = geoCalc.calculateGeodeticMeasurement(reference, userPos, pointA).getPointToPointDistance();

并且

public static double getDistance2(double lat1, double lon1, double lat2, double lon2) {
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1))
            * Math.sin(deg2rad(lat2))
            + Math.cos(deg2rad(lon1))
            * Math.cos(deg2rad(lon2))
            * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    return (dist);
}

private static double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}

private static  double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

public static Double getDistance1(double lat1, double lng1, double lat2, double lng2) {
    double earthRadius = 6371000; //meters
    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 = (Double) (earthRadius * c);
    return dist;
}

最后,

public static Double getDistance(Double lat1,Double long1,Double lat2,Double long2){
    Location startPoint=new Location("locationA");
    startPoint.setLatitude(lat1);
    startPoint.setLongitude(long1);

    Location endPoint=new Location("locationA");
    endPoint.setLatitude(lat2);
    endPoint.setLongitude(long2);

    double distance=startPoint.distanceTo(endPoint);
    return distance;
}

但到目前为止我无法得到确切的位置。所以请帮我解决我的问题。

1 个答案:

答案 0 :(得分:0)

我希望以下代码对您有所帮助:

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
locationB.setLongitude(lngB);

float distance = locationA.distanceTo(locationB);