如何通过经纬度获取两点之间的距离?

27

我想通过经纬度获取从A到B的距离。 当我运行以下代码时,它返回错误的结果。 例如,我尝试了A(31.172740,115.0081630),然后是B(30.6055980,114.3603140),结果约为3111公里。但正确的距离大约为134公里。 我的代码是:

    class btnListener implements OnClickListener{

    public void onClick(View v) {
         lat_a=lat_A.getText().toString();
         lng_a=lng_A.getText().toString();
         lat_b=lat_B.getText().toString();
         lng_b=lng_B.getText().toString();
         double a1,n1,a2,n2;
         a1=30.6055980;
         a2=Double.parseDouble(lat_b);
         n2=Double.parseDouble(lng_b);
         double R=6371;
         double D=Math.acos(Math.sin(a1)*Math.sin(a2)+Math.cos(a1)*Math.cos(a2)*Math.cos(n2-n1));
         Toast.makeText(getApplication(), "the distance is"+String.valueOf(D*R)+"km from A to B", Toast.LENGTH_SHORT).show();
    }

}

请查看以下链接:https://dev59.com/f3E85IYBdhLWcg3wgDzd - Saasha
非常感谢。我正在寻找它。 - lanyimo
4个回答

81

Android提供了一个API来获取两点之间的距离。使用:

Location.distanceBetween(
    startLatitude,
    startLongitude,
    endLatitude,
    endLongitude,
    results);

这将返回以米为单位的距离。


我发现结果是一个浮点数类型的数组。让我再试一次。谢谢。 - lanyimo
14
值得一提的是,以米为单位的距离存储在results[0]中。更多信息请参考:http://developer.android.com/reference/android/location/Location.html#distanceBetween(double,%20double,%20double,%20double,%20float[]) - cyborg86pl
2
计算出来的距离存储在results[0]中。如果results长度大于等于2,则初始方位角存储在results[1]中。如果results长度大于等于3,则最终方位角存储在results[2]中。 - Angel Koh
1
这个距离是否与在gmaps中测量的距离相匹配? - Nagendra Hari Karthick

18
LatLng startLatLng = new LatLng(startLatitude, startLongitude);
LatLng endLatLng = new LatLng(endLatitude, endLongitude)
double distance = SphericalUtil.computeDistanceBetween(startLatLng, endLatLng);

还需要添加

compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.maps.android:android-maps-utils:0.5+'

到你的gradle依赖项

距离(单位:米)


18

尝试以下代码。

public float distance (float lat_a, float lng_a, float lat_b, float lng_b ) 
{
    double earthRadius = 3958.75;
    double latDiff = Math.toRadians(lat_b-lat_a);
    double lngDiff = Math.toRadians(lng_b-lng_a);
    double a = Math.sin(latDiff /2) * Math.sin(latDiff /2) +
    Math.cos(Math.toRadians(lat_a)) * Math.cos(Math.toRadians(lat_b)) *
    Math.sin(lngDiff /2) * Math.sin(lngDiff /2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double distance = earthRadius * c;

    int meterConversion = 1609;

    return new Float(distance * meterConversion).floatValue();
}

如果你没有理解,请查看此链接,相同的代码在这里也可以找到。


1

这将得出两点之间的驾驶距离,而不是实际距离。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接