Search code examples
pythongeopy

how to pass city and country to geocode


I want to make sure I get the lat and lng for right city. For e.g there is Sydney in Australia and Sydney in Canada. This works fine

for d in listofobjs:
    location = geolocator.geocode(d['city'])
    d2 = {
        'username': d['username'],
        'latitude': location.latitude,
        'longitude': location.longitude
    }
    listofobjs2.append(d2)

But I get an error if I try location like this instead

location = geolocator.geocode(d['city'],d['country'])

I get an error when I try to read latitude from locatoion

AttributeError: 'list' object has no attribute 'latitude'

Is it possible to pass both city and country to geocode ?


Solution

  • In the documentation it is stated that geolocator.geocode can return 0,1 or more values. The method can return a list, hence the error message when you try to access it as a single structure element. Or iterate through the list and append to listofobjs2 as much as needed.

    You cannot be sure of getting exactly 1 location match. But why passing 2 parameters? I would combine them in a string like in the docs example:

    "some address NYC". So if you put your request like this:

    d['city']+" "+d['country']

    it would match the example much better

    https://geopy.readthedocs.io/en/1.10.0/