Tuesday, March 6, 2018

Distance Between Two Geographic Coordinates (Latitude and Longitude)

Using python to compute distance between two latitude and longitude points

Latitude and Longitude coordinates assume the earth is sphere in shape (i.e NOT flat). So, since the earth is a sphere, you can't use the distance formula that works for two points in a plane. Instead you will use a formular that approximates and assumes the earth is a sphere or ellipsoid namely:-
1- Vincenty formula
2- Haversine formula
3- Great-circle distance
4- Spherical Law of Cosines formula for distance calculations

Here are some Python based Geographic Coordinates distance calculations using Haversine formula and Vincenty formula.

First lets see how to calculate the distance between two point on a flat plane using the distance formula
Distance=(x2x1)2+(y2y1)2

In python it should look like this...

def distance(x1, y1, x2, y2):
dist = ((x1 - x2)**2 + (y1-y2)**2)**.5
return dist

x1, y1, x2, y2 = 3.52, 7.02, 10.55, 9.60

print (distance(x1, y1, x2, y2)) # Result is 7.49meters

Back to using Geographic Coordinates (Latitude and Longitude) assuming the earth is spherical.

Haversine formula - Calculate distance between two points latitude and longitude
The formula is given by...
Haversine formula:
a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c

where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!

from math import radians, cos, sin, sqrt, atan2
# Distance between two lat/lng coordinates in km using the Haversine formula
def getDistanceFromLatLng(lat1, lng1, lat2, lng2, miles=False): # use decimal degrees
r = 6371 # radius of the earth in km

lat_dif = lat2-lat1
lng_dif = lng2-lng1

a = sin(lat_dif/2.0)**2 + cos(lat1) * cos(lat2) * sin(lng_dif/2.0)**2

c = 2 * atan2(sqrt(a), sqrt(1 - a))
d = r * c
return d # return km

Another Version....

from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6371.0

dlon = lon2 - lon1
dlat = lat2 - lat1

a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))

distance = R * c

print("Result:", distance)

Vincenty formula - Calculate distance between two points latitude and longitude

Here we will use geopy python module which has vincenty formula in it...

The Geopy module can calculate geodesic distance between two points using the Vincenty distance formula, as class "geopy.distance.distance", and the computed distance available as attributes (e.g., miles, meters, etc.).

from geopy.distance import vincenty

lat1, lng1, lat2, lng2 = 3.52, 7.02, 10.55, 9.60

pt1 = (lat1, lng1)
pt2 = (lat2, lng2)

print(vincenty(pt1, pt2).km)

Thank you for following...