【问题标题】:Calculate distance between 2 points in google maps using python使用python计算谷歌地图中2点之间的距离
【发布时间】:2017-08-03 09:09:36
【问题描述】:

我使用 gmail 地理编码功能获得经度和纬度。现在我需要计算2点之间的距离。我找到了 Haversine 公式,它运行良好,但后来在 google js api 中,我在几何库中找到了方法 computeDistanceBetween(lat,lng)。我的问题是python有没有函数或库?

【问题讨论】:

    标签: python google-maps distance


    【解决方案1】:

    使用geopyhttps://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'
    

    【讨论】:

      【解决方案2】:
      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)))
      

      这将返回球体上各点之间的角距离。要获得长度(公里)距离,请将结果乘以地球半径。

      但是您也可以在公式集合中查找它,因此会出现一堆反对票 ;-)

      【讨论】:

      • 我的意思是在 google api 中有一个用于 python 的方法或一些用于计算 python 距离的库。
      【解决方案3】:

      您可以使用 Google Maps API 计算两点之间的距离。

      要查找两个城市之间的距离:

      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'}
      

      如果您有起点和终点的地理坐标(经纬度),请执行以下操作:

      # 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'}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-02
        • 2013-09-30
        • 1970-01-01
        • 2014-08-29
        • 2016-04-12
        • 2023-03-23
        • 2011-09-21
        相关资源
        最近更新 更多