## Distance Between Two Locations (Sphere)

Users of our US Zip Codes, US Cities and World Cities databases often need to calculate the distance between two geographic coordinates (in lat/lng). Since the earth is a sphere, you can't use the distance formula that works for two points in a plane. Instead, you should use the Haversine Formula. This formula is an approximation as it assumes the earth is a sphere when, in reality, it's an ellipsoid. However, it is fast and close enough for most uses. Feel free to use our MIT-released implementations below in JavaScript and Python.

### JavaScript

``````/* Distance between two lat/lng coordinates in km using the Haversine formula */
function getDistanceFromLatLng(lat1, lng1, lat2, lng2, miles) { // miles optional
if (typeof miles === "undefined"){miles=false;}
function square(x){return Math.pow(x, 2);}
var r=6371; // radius of the earth in km
var lat_dif=lat2-lat1;
var a=square(Math.sin(lat_dif/2))+Math.cos(lat1)*Math.cos(lat2)*square(Math.sin(lng_dif/2));
var d=2*r*Math.asin(Math.sqrt(a));
if (miles){return d * 0.621371;} //return miles
else{return d;} //return km
}
/* Copyright 2016, Chris Youderian, SimpleMaps, http://simplemaps.com/resources/location-distance
``````

### Python

``````from math import radians, cos, sin, asin, sqrt
# 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