Reputation: 179
I am very new to Google maps I want calculate the distance between two places in android.
For that I get the two places lat and lag positions for that I write the following code:
private double getDistance(double lat1, double lat2, double lon1, double lon2) {
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.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double temp = 6371 * c;
temp=temp*0.621;
return temp;
}
The above code can't give the accurate distance between two places. What is the another way to find distance please give me any suggestions.
Upvotes: 7
Views: 25595
Reputation: 1570
Based on https://stackoverflow.com/a/13206484/, with one change
double distance;
Location locationA = new Location(“Point A”);
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location(“Point B”);
locationB.setLatitude(latB);
locationB.setLongitude(lngB);
// distance = locationA.distanceTo(locationB); // in meters
distance = locationA.distanceTo(locationB)/1000; // in km
Upvotes: 20
Reputation: 11
Use code find distance meters to km and km to miles
Location locationA = new Location(“Point A”);
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location(“Point B”);
locationB.setLatitude(latB);
locationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB); // in meters
distance = locationA.distanceTo(locationB)/1000; // in km
distance = locationA.distanceTo(locationB)/1609.344; // in miles
Upvotes: 1
Reputation: 252
Just use Location.distanceTo(Location) it will give you a really distance between two different Locations.
Upvotes: 0