如何用经纬度来获得在谷歌地图V2在公里的两地之间的距离经纬度、两地、如何用、距离

2023-09-06 18:16:29 作者:与风相拥

在我的Andr​​oid应用程序, 我已经计算用户的当前位置和该用户点击地图上的点之间的距离。 我使用这个功能来计算:

In my android application, I've to calculate distance between user's current location and the point that user taps on the map. I'm using this function to calculate:

     public double CalculationByDistance(LatLng StartP, LatLng EndP) {
     int Radius=6371;//radius of earth in Km         
     double lat1 = StartP.latitude;
     double lat2 = EndP.latitude;
     double lon1 = StartP.longitude;
     double lon2 = EndP.longitude;
     double dLat = Math.toRadians(lat2-lat1);
     double dLon = Math.toRadians(lon2-lon1);
     double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2 * Math.asin(Math.sqrt(a));
    double valueResult= Radius*c;
    double km=valueResult/1;
    DecimalFormat newFormat = new DecimalFormat("####");
    int kmInDec =  Integer.valueOf(newFormat.format(km));
    double meter=valueResult%1000;
    int  meterInDec= Integer.valueOf(newFormat.format(meter));
    Log.i("Radius Value",""+valueResult+"   KM  "+kmInDec+" Meter   "+meterInDec);

    return Radius * c;
    }

但我发现了很长的距离作为结果,例如。我越来越喜欢10947公里的两个地方是只有约20米远的距离。谁能帮我?

But I'm getting very long distance as the result , for eg. I'm getting like 10947 km as the distance between two places which is only about 20 m far . Can anyone help me?

推荐答案

搜索约半正矢公式。这里有一个实现,它返回的距离在仪表:

Search about Haversine equation. here's one implementation which return the distance in Meter:

public static double haversine(double lat1, double lon1, double lat2, double lon2) {
    double dLat = Math.toRadians(lat2 - lat1);
    double dLon = Math.toRadians(lon2 - lon1);
    lat1 = Math.toRadians(lat1);
    lat2 = Math.toRadians(lat2);

    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return R * c;
}

其中R = 6371000;

Where R = 6371000;

 
精彩推荐
图片推荐