Converting Google Directions API output to a Spatial Data Format

I’ve ran into a major road block of sorts in the past month on my project. My goal is to untangle the ugly output that is returned by the Google Directions API and write it to a file thats easy to plot and read in QGIS.

I found a great script that converts the encoded polyline into a series of latitude and longitude points, which I could then again convert into a geojson or shape file format.

However I am currently trying to pull the geocoded overview line out of the Google Directions output in Python. I am getting close by using the split function, but getting hung up on all the quotation marks and backslashes that muddle up the output and confuse python.

For example, I am trying to just isolate the text in the quotes after the “”overview_polyline” : {\n “points” :” text in file below.

"start_location" : {\n                        "lat" : 53.5779983,\n                        "lng" : -113.5965706\n                     },\n                     "travel_mode" : "DRIVING"\n                  }\n               ],\n               "via_waypoint" : []\n            }\n         ],\n 
        "overview_polyline" : {\n            "points" : "m{xeIdeusTyJxADtG{@|DaJ?kRBoRFsDhJiCvIs@vCyBnKwEhKuVfu@ma@zoAcPtc@yFvAyDlBwNHsSg@uBeF{AyPcDeCqD?

\\\\a@zUgd@tyCcBnWQjz@@p`A~DfcA`FzuAoBt_@aEtTyWvq@w_@z_AuG~ViRl_Au[xgCPzn@zI`h@bQpt@nC~Z~FbwB`Cpq@`EdW~NzZhy@~jAh{AvrA~L~Rd[vw@~o@~cBbEhSxH~eAvM`bAjNjx@dTj~@dWzj@nLx[xg@rwB`h@hlBne@t{BdyA~aEtGbLx]j]vJfWhZ~}AdStl@l~AfyDtUnk@~p@dvBbXbu@rz@nmBlElUr@|VoAnS"\n         },\n         "summary" : "Yellowhead Hwy W/AB-16",\n
         "warnings" : [],\n         "waypoint_order" : []\n      }\n   ],\n   "status" : "OK"\n}\n'

I think the great thing about scripting is that most people have already done a lot of the hard work and posted it online. With basic knowledge of the language and a clear understanding of process I know I will eventually get to my goal, step by step.

I will keep puttering about, but this is my script so far which doesn’t quite get there (it is splitting things in the wrong place).

import os
import sys
import fileinput

fileToSearch  = 'newfile1.geojson'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    mystring = line
    clipped = mystring[mystring.find("overview_polyline"):mystring.find('"\n')]