Search code examples
pythonjsongeocodinggeopy

ERROR: "No JSON object can be decoded" in Geopy when extracting lat, long from geocode_url


I am using the following code:

from geopy import geocoders   

def main():
    gn = geocoders.GeoNames()
    city = 'roman'
    place, (lat, lng) = gn.geocode_url('http://www.geonames.org/advanced-search.html?q='+city+'&country=FR&featureClass=A&continentCode=&fuzzy=0.6')
    location, (lat, lon) = geocodes[0]
    print lat, lon

I want to print the first result returned from the Geopy website for a city, given the specific URL configurations (in France, feature = A, and fuzzy = .6)

However, I keep getting a "No JSON Object can be decoded" error from the above code. What's the issue?


Solution

  • You're supposed to use the JSON webservice:

    url = 'http://ws.geonames.org/searchJSON?q=%s&country=FR&featureClass=A&continentCode=&fuzzy=0.6'
    gn.geocode_url(url % city)
    

    The proper way to add more params is to use urlencode and the url geocode uses:

    from urllib import urlencode
    params = {
        'q': 'roman',
        'featureClass': 'A',
        'fuzzy': '0.6',
        'country': 'FR'
    }
    gn.geocode_url(gn.url % urlencode(params))