I get longitude and latitude using gmail geocode function. Now i need to calculate distance between 2 points. I found Haversine formula and it works well, but then in google js api i found method computeDistanceBetween(lat,lng) in the Geometry Library. My question is there a function or library for python?
4 Answers
Use geopy https://pypi.org/project/geopy/
In [39]: from geopy.distance import geodesic
In [40]: you = ("73.6490763,-43.9762069")
In [41]: me = ("73.646628,-43.970497")
In [42]: miles = geodesic(me,you).miles
In [43]: f"Miles: {miles:.2f}"
Out[43]: 'Miles: 0.20'
You can calculate distance between two points using Google Maps API.
To find distance between two cities:
import googlemaps
# Requires API key
gmaps = googlemaps.Client(key='Your_API_key')
# Requires cities name
distance = gmaps.distance_matrix('Delhi','Mumbai')['rows'][0]['elements'][0]
print(distance)
{u'distance': {u'text': u'1,418 km', u'value': 1417632},
u'duration': {u'text': u'1 day 0 hours', u'value': 87010},
u'status': u'OK'}
If you have geo coordinates(latitude and longitude) of origin and destination, then do as below:
# Requires geo-coordinates(latitude/longitude) of origin and destination
origin_latitude = 12.9551779
origin_longitude = 77.6910334
destination_latitude = 28.505278
destination_longitude = 77.327774
distance = gmaps.distance_matrix([str(origin_latitude) + " " + str(origin_longitude)], [str(destination_latitude) + " " + str(destination_longitude)], mode='walking')['rows'][0]['elements'][0]
print(distance)
{u'distance': {u'text': u'2,014 km', u'value': 2013656},
u'duration': {u'text': u'16 days 23 hours', u'value': 1464529},
u'status': u'OK'}
from math import *
def greatCircleDistance((lat1, lon1), (lat2, lon2)):
def haversin(x):
return sin(x/2)**2
return 2 * asin(sqrt(
haversin(lat2-lat1) +
cos(lat1) * cos(lat2) * haversin(lon2-lon1)))
This returns the angular distance between the points on a sphere. To get a distance in length (kilometers), multiply the result with the Earth radius.
But you could have it looked up in a formula collection as well, hence the bunch of downvotes ;-)
-
i meant is there a method in google api for python or some library for calculating distances in python. Aug 3, 2017 at 9:25
-
Keep in mind that the latitudes and longitudes that you input to the haversine function must be in radians, so maybe it's wise to convert these from degrees to radians right at the beginning of the function, since degrees are the most natural units for geolocation. For reference, see: en.wikipedia.org/wiki/… Jul 17, 2022 at 16:59
# importing googlemaps module
import googlemaps
# Requires API key
gmaps = googlemaps.Client(key='Your_API_key')
# Requires cities name
my_dist = gmaps.distance_matrix('Delhi','Mumbai')['rows'][0]['elements'][0]
# Printing the result
print(my_dist)