如何用经纬度来获得在谷歌地图V2在公里的两地之间的距离 [英] how to get distance between two places in kilometer in google map v2 using LatLng

查看:165
本文介绍了如何用经纬度来获得在谷歌地图V2在公里的两地之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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;

这篇关于如何用经纬度来获得在谷歌地图V2在公里的两地之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆