I would like to know how I can find the distance between 2 coordinates in kilometers by car, I am using the google maps API. I appreciate any contribution.
I would like to know how I can find the distance between 2 coordinates in kilometers by car, I am using the google maps API. I appreciate any contribution.
Googlemaps has the function distanceTo
official documentation of Location
Example:
Location locationA = new Location("punto A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("punto B");
locationB.setLatitude(latB);
locationB.setLongitude(lngB);
float distance = locationA.distanceTo(locationB);
The value returned is in meters.
Or you can try that function, extracted from the answer SO
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radio de la tierra en kilómetros
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
I recommend using the Location class of android, you have already implemented a method for that
Location location = new Location("localizacion 1");
location.setLatitude(0.00000); //latitud
location.setLongitude(0.00000); //longitud
Location location2 = new Location("localizacion 2");
location2.setLatitude(0.00000); //latitud
location2.setLongitude(0.00000); //longitud
double distance = location.distanceTo(location2);