Pasindu Samaranayake
Pasindu Samaranayake

Reputation: 113

How to encode latitude and longitude using urllib.parse.urlencode?

I'm using Google API to obtain the json data of nearby coffee outlets. To do this, I need to encode the latitude and longitude into the URL.

The required URL: https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee&location=22.303940,114.170372&radius=1000&maxprice=3&key=myAPIKey

The URL i'm obtaining using urlencode: https://maps.googleapis.com/maps/api/place/textsearch/json?query=coffee&location=22.303940%2C114.170372&radius=1000&maxprice=3&key=myAPIKEY

How can I remove the "%2C" in the URL? (I have shown my code below)

serviceurl_placesearch = 'https://maps.googleapis.com/maps/api/place/textsearch/json?'
    parameters = dict()
    query = input('What are you searching for?')     
    parameters['query'] = query

parameters['location'] = "22.303940,114.170372"

while True:
    radius = input('Enter radius of search in meters: ')
    try:
        radius = int(radius)
        parameters['radius'] = radius
        break
    except:
        print('Please enter number for radius')

while True:
    maxprice = input('Enter the maximum price level you are looking for(0 to 4): ')
    try:
        maxprice = int(maxprice)
        parameters['maxprice'] = maxprice
        break
    except:
        print('Valid inputs are 0,1,2,3,4')
parameters['key'] = API_key

url = serviceurl_placesearch + urllib.parse.urlencode(parameters)

I added this piece of code in to make the URL work however I don't think this is a long term solution. I'm looking for a more long term solution.

urlparts = url.split('%2C')
url = ','.join(urlparts)

Upvotes: 1

Views: 506

Answers (1)

furas
furas

Reputation: 142992

You can add safe=","

import urllib.parse

parameters = {'location': "22.303940,114.170372"}

urllib.parse.urlencode(parameters, safe=',')

Result

location=22.303940,114.170372

Upvotes: 1

Related Questions