For a pair of Latitude/longitude coordinates , calculate the distance between them
- User
For a pair of Latitude/longitude coordinates , calculate the distance between them
- Assistant
Calculating the distance between two latitude/longitude points on the Earth's surface involves using the Haversine formula, or you can use other formulas like Vincenty's formula for more precision. However, for most applications, the Haversine formula offers a good balance between simplicity and accuracy. The Haversine formula assumes a spherical model of the earth, which is accurate enough for most purposes.
Here's how you can calculate the distance using the Haversine formula in Python:
pythonimport math def haversine(lat1, lon1, lat2, lon2): # convert decimal degrees to radians lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2]) # haversine formula dlat = lat2 - lat1 dlon = lon2 - lon1 a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2 c = 2 * math.asin(math.sqrt(a)) # Radius of earth in kilometers. Use 3956 for miles r = 6371 return c * r # Example usage lat1, lon1 = 40.748817, -73.985428 # New York City's Lat/Lon lat2, lon2 = 51.5074, -0.1278 # London's Lat/Lon distance = haversine(lat1, lon1, lat2, lon2) print(f"Distance: {distance} kilometers")This example calculates the distance between New York City and London. Keep in mind that to switch the output to miles, you can change the radius of the Earth (
r) in thehaversinefunction definition to 3956 miles.The haversine formula is:
[a = \sin^2(\frac{\Delta\phi}{2}) + \cos(\phi_1) \cdot \cos(\phi_2) \cdot \sin^2(\frac{\Delta\lambda}{2})]
[c = 2 \cdot \text{atan2}( \sqrt{a}, \sqrt{1-a} )]
[d = R \cdot c]
Where,
- (\Delta\phi) is the difference in latitude radians
- (\Delta\lambda) is the difference in longitude radians
- (\phi_1) and (\phi_2) are the latitude of point 1 and latitude of point 2 in radians.
- (R) is the Earth’s radius (mean radius = 6,371 km)
- (d) is the distance between the two points along the surface of the sphere
Remember, this formula assumes a spherical Earth, which introduces a small error (up to about 0.5%) because the actual shape of the Earth is slightly ellipsoidal (oblate spheroid). For most everyday purposes, especially over short distances, this error is negligible.