Utilizing Python to send API requests to Google Directions

In the last post we talked about how to manually enter API requests into any browser and get a geoJSON file back that is readable in QGIS. In order to complete my project efficiently, I needed to find out how to pass these requests to the Google Direction API through Python so I could eventually pass in a large spreadsheet or database of origins and destinations and get back a series of files.

The first step in the process was to learn how to send a url request through python. I found directions on the google maps API website to preform a simple geocoding request, but when I passed it into python I got all sorts of errors! The code suggested by Google looks like this:

Screen Shot 2015-05-18 at 1.53.57 PM

After some quick googling I found that the urllib2 library isn’t in use for Python 3.0 and up. So I found that the replacement was urllib.request. Easy enough! I added that to the code, and included the print(jsongeocode) to the end and ta-da! it spits out the geoJSON response from the server that is now stored as a variable in Python for me. I modified the script so that it was sending a request to the directions API instead of the geocoding API simply by using the url example shown in my blog post below. Obviously I will want to refine this a bit more so that I can pass in the origin and destination as quick variables and have it generate the entire url from that. We will work on that in the next few blog posts. The basic code I made is located below for returning a route file from Edmonton to Calgary.

url="https://maps.googleapis.com/maps/api/directions/json?%s" % direction1

response = urllib.request.urlopen(url)
jsongeocode = response.read()



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s