I have a list of tuples that I want to iterate through and send a http request via the python requests module.
api_schedule = [
{'destination': (51.490527, 0.267840), 'id': 'trial_a', 'origin': (51.430732, 0.239308)},
{'destination': (51.429488, 0.239060), 'id': 'trial_b', 'origin': (51.490518, 0.267578)}]
The origin and destination coordinates are proving difficult to format correctly. The Google Directions API expects them in the format lat,lng where the lat and lng are float
I iterate through the list of dictionaries like so:
for pair in api_schedule:
departure_time = time.time()
origin_lat = str(pair['origin'][0])
origin_lng = "," + str(pair['origin'][1])
origin = origin_lat + origin_lng
destination_lat = str(pair['destination'][0])
destination_lng = "," + str(pair['destination'][1])
destination = destination_lat + destination_lng
params = {
"origin" : origin,
"destination" : destination
"key" : api_Key,
"departure_time" : departure_time,
"mode" : mode
}
request = requests.Request('GET', url_raw, params=params).prepare()
print request.url
However, this returns %2C in place of ,:
https://maps.googleapis.com/maps/api/directions/json?origin=51.430732%2C0.239308&destination=51.490527&destination=0.26784
How do I iterate through a list of tuples like this and use requests to formula the parameters correctly?
When I try without the above manipulation, requests views the origin and destination data as lists and thus creates two params like so:
https://maps.googleapis.com/maps/api/directions/json?origin=51.430732&origin=0.239308
Desired output:
https://maps.googleapis.com/maps/api/directions/json?origin=51.430732,0.239308&destination=51.490527,0.26784
https://maps.googleapis.com/maps/api/directions/json?origin=51.430732,0.239308&destination=51.490527,0.26784instead ofhttps://maps.googleapis.com/maps/api/directions/json?origin=51.430732&origin=0.239308orhttps://maps.googleapis.com/maps/api/directions/json?origin=51.430732%2C0.239308&destination=51.490527&destination=0.26784%2Cis entirely correct and expected in a URL. Google will decode that for you. If you were to use your 'desired output' URL in a browser, your browser would also encode the comma.