25

How can i find the distance between two latitude & longitude points


For one of the latitude & longitude points i have it in database & another one i want to use current position of the mobile

Which one should i need to use them among below::

  • android location provider
  • Google API
  • Mathematical Calculation

note:: Any demo code sample will be useful

Devrath
  • 42,072
  • 54
  • 195
  • 297
  • possible duplicate of [Find distance between two points on map using Google Map API V2](http://stackoverflow.com/questions/14394366/find-distance-between-two-points-on-map-using-google-map-api-v2) – David Mar 22 '14 at 11:38
  • https://stackoverflow.com/questions/8049612/calculating-distance-between-two-geographic-locations – General Grievance Aug 29 '23 at 15:20

2 Answers2

57

You can use the built in algorithm:

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

update: (I don't have any error with this)

LatLng latLngA = new LatLng(12.3456789,98.7654321);
LatLng latLngB = new LatLng(98.7654321,12.3456789);

Location locationA = new Location("point A");
locationA.setLatitude(latLngA.latitude);
locationA.setLongitude(latLngA.longitude);
Location locationB = new Location("point B");
locationB.setLatitude(latLngB.latitude);
locationB.setLongitude(latLngB.longitude);

double distance = locationA.distanceTo(locationB);
Surya Prakash Kushawah
  • 3,185
  • 1
  • 22
  • 42
David
  • 2,331
  • 4
  • 29
  • 42
14

You can use the Haversine algorithm. Another user has already coded a solution for this:

public double CalculationByDistance(double initialLat, double initialLong,
                            double finalLat, double finalLong){
int R = 6371; // km
double dLat = toRadians(finalLat-initialLat);
double dLon = toRadians(finalLong-initialLong);
lat1 = toRadians(lat1);
lat2 = toRadians(lat2);

double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
return R * c;
}

public double toRadians(deg) {
  return deg * (Math.PI/180)
}

Source: https://stackoverflow.com/a/17787472/3449528

Community
  • 1
  • 1
Emilio
  • 326
  • 1
  • 9