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

前端 未结 3 386
隐瞒了意图╮
隐瞒了意图╮ 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:17
    LatLng startLatLng = new LatLng(startLatitude, startLongitude);
    LatLng endLatLng = new LatLng(endLatitude, endLongitude)
    double distance = SphericalUtil.computeDistanceBetween(startLatLng, endLatLng);
    

    also add

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

    to your gradle dependencies

    Distance in meters

    0 讨论(0)
  • 2020-12-06 10:24

    There is an api provided by android itself to get distance between two points. Use:

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

    which returns distance in meters.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题