Chcem sa dynamicky dopytovať na Mapy Google prostredníctvom rozhrania Google Directions API. Táto požiadavka napríklad vypočíta trasu z Chicaga, IL do Los Angeles, CA cez dva body v Joplin, MO a Oklahoma City, OK:
Vráti výsledok vo formáte JSON.
Ako to môžem urobiť v jazyku Python? Chcem poslať takúto požiadavku, prijať výsledok a analyzovať ho.
Odporúčam použiť úžasnú knižnicu requests:
import requests
url = 'http://maps.googleapis.com/maps/api/directions/json'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below
Obsah odpovede JSON: http://docs.python-requests.org/en/latest/user/quickstart/#json-response-content.
Použite knižnicu requests, pekne vypíšte výsledky, aby ste mohli lepšie lokalizovať kľúče/hodnoty, ktoré chcete extrahovať, a potom použite vnorené slučky for na analýzu údajov. V príklade extrahujem smer jazdy krok za krokom.
import json, requests, pprint
url = 'http://maps.googleapis.com/maps/api/directions/json?'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)
# test to see if the request was valid
#print output['status']
# output all of the results
#pprint.pprint(output)
# step-by-step directions
for route in output['routes']:
for leg in route['legs']:
for step in leg['steps']:
print step['html_instructions']