Tag Archives: How to Calculate the Distance

Python: How to Calculate the Distance of Latitude and Longitude

 1     def geodistance(self, lng1, lat1, lng2, lat2):
 2         # lng1,lat1,lng2,lat2 = (120.12802999999997,30.28708,115.86572000000001,28.7427)
 3         lng1, lat1, lng2, lat2 = map(radians, [float(lng1), float(lat1), float(lng2), float(lat2)])  # Latitude and longitude to radians
 4         dlon = lng2 - lng1
 5         dlat = lat2 - lat1
 6         a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
 7         distance = 2 * asin(sqrt(a)) * 6371 * 1000  # Average radius of the Earth, 6371km
 8         # Unit: meter
 9         distance = round(distance, 3)
10         return distance