8-Bit Borges
8-Bit Borges

Reputation: 10033

Google Places Api - pass an address with the right encoding

In order to make a Google Places Api call, I use this function:

def build_URL(search_text='',types_text=''):
    base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'     
    key_string = '?key=mykey'                                       
    query_string = '&query='+urllib.quote(search_text)
    sensor_string = '&sensor=false'                                            
    type_string = ''
    if types_text!='':
        type_string = '&types='+urllib.quote(types_text)                        
    url = base_url+key_string+query_string+sensor_string+type_string
    return url

but the address I'm passing as an argument has encoding issues:

   print(build_URL(search_text='R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'))

I have tried 'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'.encode('utf-8'), to no avail. I get the error:

{
error_message: "Invalid request. One of the input parameters contains a non-UTF-8 string.",
html_attributions: [ ],
results: [ ],
status: "INVALID_REQUEST"
}

my script also has #-*- coding: utf-8 -*- at the top.

how do I fix this?

Upvotes: 1

Views: 1360

Answers (1)

A workaround may be to use the Unidecode package which makes a best-attempt to represent Unicode in ASCII:

search_text_unicode=u'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'

search_text_ascii = unidecode(search_text_unicode)
# check the conversion
print(search_text_ascii) # R. Fradique Coutinho, 1332 - Pinheiros, Sao Paulo - SP, 05416-001, Brazil
# got valid ASCII which can be passed to your function
print(build_URL(search_text=search_text_ascii))

upon which the returned URL is recognized in the Google Maps API.

Upvotes: 1

Related Questions