How can I get the distance between two point by latlng?

前端 未结 3 394
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 09:49

I want to get the distance from A to B by latlng.When i run my app with the following code,it return a wrong result. Fx i tryed A( 31.172740,115.0081630) ,then B(30.6055980,

3条回答
  •  粉色の甜心
    2020-12-06 10:25

    Try below code.

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

    If you didn't understood, please check this link, same code available here.

提交回复
热议问题