Google Map Direction API

GOAL: Make a call to Google Map API to get the duration time of a transit travel between two geolocations

I've been working on making adding a feature to Rideminder - having an estimated time to double check along with the distance. I want to do this so I'm not solely dependent on Firebase and if Firebase goes down for a bit, I have a back up.

So I started with research on how to make Google Map Direction API calls. It turns out I can get a response in either XML or Json and since I used XML already in my project, I thought that Json would be fun to learn.docsThe docs are super simple and I went straight to the tab for "travel time." It had a great example of how to make the API call and what actually comes out from that. The example in the docs had actual addresses, so I had to google what it would look like with geolocation, which wasn't difficult.I wrote a quick script using these libraries:

  • simplejson - this will encode and decode json using python
  • urllib - this will get the data from the internet and lets you "open" it
  • json - this also encode and decodes json, but it different methods, I used the json.loads method
  • pprint - this makes it easier to read the json object, it gives it nice spaces

jsonpprintI was able to make the API call and I got back a beautiful json object with all the data! YEAH! So I ran it in python -i (which makes it interactive) and I played around calling my json to be able to pull out just the duration time. So my example has a duration of "22 mins." I split it up so now I have u'22.playingwithjsonSo I think I'll use milliseconds for my timestamp so I can add the duration time in milliseconds to the current time so I can get do time.time which gives me the seconds since the epoch as a floating point number.milliseconds*NOTE: make sure you change your split[0] list into an int so you can actually get the milliseconds vs getting whatever number you have printed out 6000 times*Once I was able to get the duration time into milliseconds and add it to the current time, I was done. I spent some time modularizing my code so it can be more generic.

Ta da!

 

Click to get my working script

modcode

Previous
Previous

Google Map Arrival Time into Datetime Object

Next
Next

gratitude