微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 如何通过latlng获得两点之间的距离?

我想通过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();
    }

}

解决方法

请尝试下面的代码.
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,这里提供相同的代码.

原文地址:https://www.jb51.cc/android/311849.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐