【问题标题】:How can I get the distance between two point by latlng?如何通过 latlng 获得两点之间的距离?
【发布时间】:2012-02-08 13:32:50
【问题描述】:

我想通过 latlng 获取从 A 到 B 的距离。当我使用以下代码运行我的应用程序时,它返回错误的结果。 Fx 我试了A(31.172740,115.0081630),然后B(30.6055980,114.3603140),结果大约是3111km。但是正确的距离大约是134km。 我的代码是:

    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();
    }

}

【问题讨论】:

标签: android gps


【解决方案1】:

android 本身提供了一个 api 来获取两点之间的距离。使用:

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

返回以米为单位的距离。

【讨论】:

  • 我发现结果是一个浮点类型的数组。让我再试一次。谢谢。
  • 值得一提的是,以米为单位的距离存储在 results[0] 中。更多信息:developer.android.com/reference/android/location/…
  • 计算出的距离存储在 results[0] 中。如果 results 的长度为 2 或更大,则初始方位存储在 results[1] 中。如果 results 长度为 3 或更大,则最终方位存储在 results[2] 中。
  • 这个距离与gmaps中测量的距离匹配吗?
【解决方案2】:

试试下面的代码。

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();
}

如果您不理解,please check this link,此处提供相同的代码。

【讨论】:

    【解决方案3】:
    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 依赖项

    距离以米为单位

    【讨论】:

      【解决方案4】:

      使用google距离Api获取实际距离

      https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=lat,lng&destinations=lat,lng&key={your谷歌地图键}&mode=driving

      它将以公里为单位返回距离。

      【讨论】:

        猜你喜欢
        • 2020-01-12
        • 1970-01-01
        • 2019-07-26
        • 2014-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-25
        相关资源
        最近更新 更多