Search code examples
pythongoogle-mapsgoogle-apiurllibstreet-address

Error while using Google's findplacefromtext - InvalidURL


I am trying to get details for addresses using Google API's findplacefromtext. This is how my code looks like:

def get_google_address(address):
    API_KEY = 'MY_API_KEY'
    URL = ('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={add}&inputtype=textquery&fields=formatted_address,name,geometry&key={API_KEY}').format(add=address,API_KEY=API_KEY)
    print(URL)
    response = urllib.request.urlopen(URL)
    data = json.load(response)
    return (data)

If I call the function as follows: get_google_address('1600 amphitheatre pkwy mountain view ca'), I get this error:

InvalidURL: URL can't contain control characters. '/maps/api/place/findplacefromtext/json?input=1600 amphitheatre pkwy mountain view ca&inputtype=textquery&fields=formatted_address,name,geometry&key=API_KEY' (found at least ' ')

However, if I paste the URL in a browser, it works. Please let me know what I am missing. The URL is like this: https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=1600 amphitheatre pkwy mountain view ca&inputtype=textquery&fields=formatted_address,name,geometry&key=API_KEY


Solution

  • Based on comment by @geocodezip, the URL needed to be encoded:

    dict1 = {'input':address, 'key':API_KEY}
    qstr = urllib.parse.urlencode(dict1) 
    URL = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json?inputtype=textquery&fields=formatted_address,name,geometry&'
    URL = URL + qstr
    response = urllib.request.urlopen(URL)
    data = json.load(response)
    return (data)