Calculate distance between 2 points in google maps using python

Question:

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?

Asked By: Ilya Levikov

||

Answers:

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 😉

Answered By: Alfe

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'}
Answered By: Om Prakash

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'
Answered By: Mee Heer

https://www.geeksforgeeks.org/python-calculate-distance-duration-two-places-using-google-distance-matrix-api/

# 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)
Answered By: jangles
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.