当我使用geopy根据经度和纬度计算2个地址之间的距离时,它可以在单个数据对上正常工作.但是当有更多数据时,它总是给我这个错误:
File “/Library/Python/2.7/site-packages/geopy/geocoders/osm.py”, line 193, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File “/Library/Python/2.7/site-packages/geopy/geocoders/base.py”, line 171, in _call_geocoder
raise GeocoderServiceError(message)
geopy.exc.GeocoderServiceError: urlopen error [Errno 65] No route to host
你知道我怎么能避免这个问题?
我的代码很简单:(为此输入的数据有很多对数据)
from geopy.geocoders import Nominatim
from geopy.distance import vincenty
def calculate_distance(add1, add2):
geolocator = Nominatim()
location1 = geolocator.geocode(add1)
al1 = (location1.latitude, location1.longitude)
location2 = geolocator.geocode(add2)
al2 = (location2.latitude, location2.longitude)
distce = vincenty(al1, al2).miles
return distce
最佳答案
def get_level1_locations(lat_lng):
elems = lat_lng.split(',')
url = "http://maps.googleapis.com/maps/api/geocode/json?"
url += "latlng=%s,%s&sensor=false" % (float(elems[0]), float(elems[1]))
v = urlopen(url).read()
j = json.loads(v)
if len(j['results'])>0:
components = j['results'][0]['address_components']
location_list=[]
for c in components:
if "locality" in c['types']:
location_list.append(c['long_name'])
if "administrative_area_level_1" in c['types']:
location_list.append(c['long_name'])
if "country" in c['types']:
location_list.append(c['long_name'])
location = ', '.join(filter(None, location_list))
return location
return ''