使用地理编码获取两个位置之间的距离
getting distance between two location using geocoding
我想使用 google API 查找两个位置之间的距离。我希望输出看起来像 - "The distance between location 1 and location 2 is 500 miles ( distance here is example purposes )",但我如何才能获得所需的输出,因为当前程序正在显示各种输出(我无法使用它来获得所需的输出)。你们能告诉我方法吗,或者告诉我具体的步骤是什么?
import urllib
import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
try: js = json.loads(str(data))
except: js = None
if 'status' not in js or js['status'] != 'OK':
print '==== Failure To Retrieve ===='
print data
continue
print json.dumps(js, indent=4)
lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
print 'lat',lat,'lng',lng
location = js['results'][0]['formatted_address']
print location
Google 有一个特定的 api,叫做 Google Maps Distance Matrix API.
Distance & duration for multiple destinations and transport modes.
Retrieve duration and distance values based on the recommended route
between start and end points.
如果您只需要地球上两点之间的距离,您可能需要使用 Haversine formula
如果您知道 lat
和 lon
,请使用 geopy 包:
In [1]: from geopy.distance import great_circle
In [2]: newport_ri = (41.49008, -71.312796)
In [3]: cleveland_oh = (41.499498, -81.695391)
In [4]: great_circle(newport_ri, cleveland_oh).kilometers
Out[4]: 864.4567616296598
我想使用 google API 查找两个位置之间的距离。我希望输出看起来像 - "The distance between location 1 and location 2 is 500 miles ( distance here is example purposes )",但我如何才能获得所需的输出,因为当前程序正在显示各种输出(我无法使用它来获得所需的输出)。你们能告诉我方法吗,或者告诉我具体的步骤是什么?
import urllib
import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
while True:
address = raw_input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.urlencode({'sensor':'false', 'address': address})
print 'Retrieving', url
uh = urllib.urlopen(url)
data = uh.read()
print 'Retrieved',len(data),'characters'
try: js = json.loads(str(data))
except: js = None
if 'status' not in js or js['status'] != 'OK':
print '==== Failure To Retrieve ===='
print data
continue
print json.dumps(js, indent=4)
lat = js["results"][0]["geometry"]["location"]["lat"]
lng = js["results"][0]["geometry"]["location"]["lng"]
print 'lat',lat,'lng',lng
location = js['results'][0]['formatted_address']
print location
Google 有一个特定的 api,叫做 Google Maps Distance Matrix API.
Distance & duration for multiple destinations and transport modes.
Retrieve duration and distance values based on the recommended route between start and end points.
如果您只需要地球上两点之间的距离,您可能需要使用 Haversine formula
如果您知道 lat
和 lon
,请使用 geopy 包:
In [1]: from geopy.distance import great_circle
In [2]: newport_ri = (41.49008, -71.312796)
In [3]: cleveland_oh = (41.499498, -81.695391)
In [4]: great_circle(newport_ri, cleveland_oh).kilometers
Out[4]: 864.4567616296598