Search code examples
pythongoogle-mapsdistance

Calculate distance between 2 points in google maps using python


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?


Solution

  • 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 ;-)