北京的地理编码问题

问题描述 投票:0回答:1

我正在尝试获取两个城市的名称,然后计算两个城市之间的距离。但在测试几个城市时,我遇到了一个关于“北京”的奇怪问题。

我首先获取两个城市的坐标,这就是问题开始的地方

def get_coordinates(city):
    geolocator = Nominatim(user_agent="distance_visualizer")
    location = geolocator.geocode(city)
    return location.latitude, location.longitude

但是当使用“北京”进行测试时,我收到错误。

WARNING:urllib3.connectionpool:Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Read timed out. (read timeout=1)")': /search?q=Beijing&format=json&limit=1
WARNING:urllib3.connectionpool:Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='nominatim.openstreetmap.org', port=443): Read timed out. (read timeout=1)")': /search?q=Beijing&format=json&limit=1

但是当我回去使用“Peking”时,它工作正常,返回

(39.9057136, 116.3912972)

这是北京的坐标。我很困惑,不知道问题是什么?为什么我使用哪个名字很重要?事实上,如果尝试北京的话,出现错误会更有意义。

python geocoding
1个回答
0
投票

您遇到的问题可能与您正在使用的地理编码服务有关,在本例中为 OpenStreetMap 的 Nominatim。该服务区分大小写,对于同一位置的不同名称可能会产生不同的结果或行为。

在这个具体案例中,问题可能是由于“Beijing”是现代名称,而“Peking”是同一城市的更古老的传统名称。地理编码服务可能会以不同的方式处理不同的名称,并且可能无法按预期识别“北京”。

要处理此类情况,您可以尝试以下方法:

location = geolocator.geocode("Beijing, China")

或者这个: def get_坐标(城市): 地理定位器 = Nominatim(user_agent="distance_visualizer") 尝试: 位置 = geolocator.geocode(城市) 返回位置.纬度,位置.经度 except (AttributeError, GeocoderTimedOut, GeocoderServiceError) as e: print(f"地理编码 {city} 错误:{e}") 无返回

© www.soinside.com 2019 - 2024. All rights reserved.