Geocoding troubles with Beijing

24 Views Asked by At

I am trying to get the names of two cities then calculate the distance between the two cities. But when testing a few cities, I ran into a bizarre problem with 'Beijing'.

I'm starting by getting the coordinates of both cities which is where the problem starts

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

But when testing with 'Beijing' I'm getting an error.

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

However when I went back and used 'Peking', it worked fine, returning

(39.9057136, 116.3912972)

which are the coordinates for Beijing. I'm confused as to what the problem is? Why does it matter which name I use? In fact it would make more sense for there to be an error if trying Peking.

1

There are 1 best solutions below

0
Andrei Norma On

The issue you're encountering is likely related to the geocoding service you're using, in this case, Nominatim from OpenStreetMap. The service is case-sensitive and may have different results or behavior for different names of the same location.

In this specific case, the issue might be due to the fact that "Beijing" is the modern name, while "Peking" is the older, traditional name for the same city. Geocoding services might handle different names differently, and it's possible that "Beijing" is not recognized as expected.

To handle such cases, you can try the following:

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

or this:

def get_coordinates(city):
    geolocator = Nominatim(user_agent="distance_visualizer")
    try:
        location = geolocator.geocode(city)
        return location.latitude, location.longitude
    except (AttributeError, GeocoderTimedOut, GeocoderServiceError) as e:
        print(f"Error geocoding {city}: {e}")
        return None