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,
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
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.
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.