Why would you use Google Maps API?
I have started this project with a single question in my mind. When should I leave my home to get in time at work and when is the lowest traffic to go out in my car.
Bucharest is on the 6th place in terms of traffic jam worldwide, so this is a serious issue not only for me but also for local transportation companies (couriers), public transportation companies, delivery companies, and so many other players.
As a company, you can use this simple trick to optimize your routes, your delivery time and all of this can lead to happy customers and of course to lower your costs.
What do you need?
1. Google Account (to link python with the Google Maps API)
2. Python (I use python 3.7)
Get the API Key from Google Maps
1. Navigate to: https://developers.google.com/maps/documentation/javascript/get-api-key
2. Press on “Get started” as below:
3. In the new window select the option that you want for the Google API (in my case I will use Routes to scrape the time and distance).
4. Click on Continue
5. Create a new project:
6. Enable Billing. Even if you are not going to pay for the requests you billing account needs to be set to get access to Google Maps API
7. Now you have to enable your API. Usually right form the other window it pops up the enabling window, but if this does not happen you can check here.
8. Copy your new Google Maps API key:
Now it’s time for Python
Necessarily libraries: urllib.request, json, datetime, time, csv and because I need this query to be done at every 5 minutes I have used also the schedule module.
Here is the code, where you have to replace the origin and destination coordinates (latitude and longitude), the path of ou output CSV file and also your API key obtained above.
The replacement is marked with […………….]
……………………………………………………
import urllib.request
import json
from datetime import datetime
import schedule
import time
import csv
# get credentials API https://console.developers.google.com/apis/credentials?project=otopeni-buchares-1566385359085
# billing info: https://console.cloud.google.com/billing/01F5E9-08EAED-D1187E?project=otopeni-buchares-1566385359085
def mainJob(origin_lat, origin_lon, dest_lat, dest_lon, way):
API_key = ‘[…………….]‘
url = ‘https://maps.googleapis.com/maps/api/distancematrix/json?origins=’
url = url + str(origin_lat)
url = url + ‘,’
url = url + str(origin_lon)
url = url + ‘&destinations=’
url = url + str(dest_lat)
url = url + ‘,’
url = url + str(dest_lon)
url = url + ‘&departure_time=now&key=’
url = url + API_key
page = urllib.request.urlopen(url)
data = json.loads(page.read().decode())
# for key, values in data.items():
# print(key)
destination_address = data[‘destination_addresses’]
origin_address = data[‘origin_addresses’]
details = data[‘rows’]
details = details[0]
details = details[‘elements’]
details = details[0]
distance = details[‘distance’]
distance_text = distance[‘text’]
distance_value = distance[‘value’]
duration = details[‘duration’]
duration_text = duration[‘text’]
duration_value = duration[‘value’]
duration_in_traffic = details[‘duration_in_traffic’]
duration_in_traffic_text = duration_in_traffic[‘text’]
duration_in_traffic_value = duration_in_traffic[‘value’]
status = details[‘status’]
data_row = []
#timestamp
now = datetime.now()
now_string = now.strftime(“%d/%m/%Y %H:%M:%S”)
data_row.append(now_string)
#rest of the data from JSON
data_row.append(destination_address)
data_row.append(origin_address)
data_row.append(distance_text)
data_row.append(distance_value)
data_row.append(duration_text)
data_row.append(duration_value)
data_row.append(duration_in_traffic_text)
data_row.append(duration_in_traffic_value)
#avg km/h
km_h = ((distance_value/1000) * 60) / (duration_in_traffic_value/60)
data_row.append(km_h)
data_row.append(origin_lat)
data_row.append(origin_lon)
data_row.append(dest_lat)
data_row.append(dest_lon)
data_row.append(way)
print(data_row)
#csv file data
filepathCSV = r’[…………….].csv’
with open(filepathCSV, ‘a’, encoding=’utf-8′, newline=”) as csvfile:
xwriter = csv.writer(csvfile)
xwriter.writerow(data_row)
#repeat schedule
def goWay():
origin_lat_go = […………….]
origin_lon_go = […………….]
dest_lat_go = […………….]
dest_lon_go = […………….]
wayDef = ‘go’
mainJob(origin_lat=origin_lat_go, origin_lon=origin_lon_go, dest_lat=dest_lat_go, dest_lon=dest_lon_go, way=wayDef)
def backWay():
origin_lat_go = […………….]
origin_lon_go = […………….]
dest_lat_go = […………….]
dest_lon_go = […………….]
wayDef = ‘back’
mainJob(origin_lat=origin_lat_go, origin_lon=origin_lon_go, dest_lat=dest_lat_go, dest_lon=dest_lon_go, way=wayDef)
goWay()
backWay()
schedule.every(5).minutes.do(goWay)
schedule.every(5).minutes.do(backWay)
while True:
schedule.run_pending()
time.sleep(1)
…………………………………………………………
Build a visualization over the data
If you want your data to be more meaningful, just build a data viz over it 🙂 … I did it using Tableau Software really fast.
btw: this is the time to get from Miliari to Pipara and back today 🙂