0
votes

I have a function that calls up google API:

def get_lat_long(place):
    place = re.sub('\s','+', str(place), flags=re.UNICODE)
    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + place
    content = urllib2.urlopen(url).read()

    obj = json.loads(content)
    results = obj['results']

    lat = long = None
    if len(results) > 0:
        loc = results[0]['geometry']['location']
        lat = float(loc['lat'])
        long = float(loc['lng'])

    return [lat, long]

However, when I enter 師大附中 as a parameter,I get the error:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) 

I tried doing str(place).encode('utf-8'), but I don't think that's the problem. I think it's because the function cannot read Chinese characters, so it needs to first convert Chinese characters to a unicode string before it reads it? That's just a guess though.

1
1. Which Python version? 2. What line does the error occur? Can you trim your example to just that line? 3. str(place).encode('utf-8') doesn't make much sense, str is doing encoding/decoding by itselfKarol S
My Python version is 2.7. and the line I get the error in is 2nd line of the snippet I posted.jason adams
What is the type of place? unicode?Karol S

1 Answers

0
votes

Assuming that place is of unicode type, you need to do something like this:

def get_lat_long(place):
    place = urllib.quote_plus(place.encode('utf-8'))
    url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + place