1

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)
2
  • %2C is the encoding of the comma in Percent Encoding. Is the API you're hitting requiring a literal comma as opposed to the percent-encoded version? Commented Feb 11, 2020 at 0:12
  • @DonRowe , if i do not have a literal comma, the json output cannot be processed my json.loads(), hence the API does require a literal comma, at least for the sake of obtaining json data. Commented Feb 11, 2020 at 22:50

1 Answer 1

1

You can add safe=","

import urllib.parse

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

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

Result

location=22.303940,114.170372
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.