Plot Route On Google Maps With Python

Photo by Annie Spratt on Unsplash

Prerequisites

pip install -U googlemaps
import googlemaps gmaps = googlemaps.Client(key='YOUR API KEY')

Get Geolocation of the Addresses

#short form of address, such as country + postal code 
geocode_result = gmaps.geocode('singapore 018956')
#full address geocode_result = gmaps.geocode("10 Bayfront Ave, Singapore 018956") #a place name
geocode_result = gmaps.geocode("zhongshan park")
#Chinese characters
geocode_result = gmaps.geocode('滨海湾花园')
#place name/restaurant name
geocode_result = gmaps.geocode('jumbo seafood east coast')
print(geocode_result[0]["formatted_address"]) print(geocode_result[0]["geometry"]["location"]["lat"]) print(geocode_result[0]["geometry"]["location"]["lng"])
1206 ECP, #01-07/08 East Coast Seafood Centre, Singapore 449883 1.3051669, 
103.930673

Reverse Geocoding

reverse_geocode_result = gmaps.reverse_geocode((1.3550021,103.7084641)) print(reverse_geocode_result[0]["formatted_address"]) #output : '87 Farrer Dr, Singapore 259287'

Check the Distance Between Locations

from datetime import datetime, timedelta gmaps.distance_matrix(
origins=geocode_result[0]['formatted_address'],
destinations=reverse_geocode_result[0]["formatted_address"],
departure_time=datetime.now() + timedelta(minutes=10))
{
'destination_addresses': ['87 Farrer Dr, Singapore 259287'],
'origin_addresses': ['1206 ECP, #01-07/08 East Coast Seafood Centre, Singapore 449883'],
'rows': [{
'elements': [{
'distance': {'text': '22.2 km', 'value': 22219},
'duration': {'text': '24 mins', 'value': 1442},
'duration_in_traffic': {'text': '22 mins', 'value': 1328}, 'status': 'OK'}]
}],
'status': 'OK'
}

Get Directions Between Locations

directions_result = gmaps.directions(
geocode_result[0]['formatted_address'],
reverse_geocode_result[0]["formatted_address"],
mode="transit",
arrival_time=datetime.now() + timedelta(minutes=0.5))
[{
'bounds':
{'northeast': {'lat': 1.3229677, 'lng': 103.9314612},
'southwest': {'lat': 1.2925606, 'lng': 103.8056495}},
'copyrights': 'Map data ©2021 Google',
'legs': [{
'arrival_time': {'text': '9:16pm', 'time_zone': 'Asia/Singapore', 'value': 1611321373},
'departure_time': {'text': '7:59pm', 'time_zone': 'Asia/Singapore', 'value': 1611316750},
'distance': {'text': '18.0 km', 'value': 17992},
'duration': {'text': '1 hour 17 mins', 'value': 4623}, 'end_address': '87 Farrer Dr, Singapore 259287',
'end_location': {'lat': 1.3132547, 'lng': 103.8070619}, 'start_address': '1206 ECP, #01-07/08 East Coast Seafood Centre, Singapore 449883',
... {'distance': {'text': '0.1 km', 'value': 106},
'duration': {'text': '1 min', 'value': 76},
'end_location': {'lat': 1.305934, 'lng': 103.9306822}, 'html_instructions': 'Turn <b>left</b>',
'maneuver': 'turn-left',
'polyline': {'points': 'q{}Fk_jyRM?KAIAE@a@DQBGDEBGDIF_@LQD'}, 'start_location': {'lat': 1.3050507, 'lng': 103.9309369}, 'travel_mode': 'WALKING'},
... }]
waypoints = [
"Chinatown Buddha Tooth Relic Temple",
"Sentosa Island, Singapore",
"National Gallery Singapore",
"Botanic Garden, Singapore",
"Boat Quay @ Bonham Street, Singapore 049782"
]
results = gmaps.directions(
origin = "Fort Canning Park, Singapore",
destination = "Raffles Hotel, Singapore",
waypoints = waypoints,
optimize_waypoints = True,
departure_time=datetime.now() + timedelta(hours=1))
for i, leg in enumerate(results[0]["legs"]):
print("Stop:" + str(i),
leg["start_address"],
"==> ",
leg["end_address"],
"distance: ",
leg["distance"]["value"],
"traveling Time: ",
leg["duration"]["value"] )

Plot Route on Google Maps

locations = [
"Fort Canning Park, Singapore",
"Chinatown Buddha Tooth Relic Temple",
"Sentosa Island, Singapore",
"National Gallery Singapore",
"Boat Quay @ Bonham Street, Singapore 049782",
"Botanic Garden, Singapore",
"Raffles Hotel, Singapore"
]

markers = ["color:blue|size:mid|label:" + chr(65+i)
+ "|" + r for i, r in enumerate(locations)]
result_map = gmaps.static_map(
center=routes[0],
scale=2,
zoom=12,
size=[640, 640],
format="jpg",
maptype="roadmap",
markers=markers,
path="color:0x0000ff|weight:2|" + "|".join(locations))
marker_points = [] 
waypoints = []
#extract the location points from the previous directions function for leg in results[0]["legs"]:
leg_start_loc = leg["start_location"]
marker_points.append(f'{leg_start_loc["lat"]},{leg_start_loc["lng"]}')
for step in leg["steps"]:
end_loc = step["end_location"]
waypoints.append(f'{end_loc["lat"]},{end_loc["lng"]}')
last_stop = results[0]["legs"][-1]["end_location"] marker_points.append(f'{last_stop["lat"]},{last_stop["lng"]}')
markers = ["color:blue|size:mid|label:" + chr(65+i)
+ "|" + r for i, r in enumerate(marker_points)]
result_map = gmaps.static_map(
center=waypoints[0],
scale=2,
zoom=13,
size=[640, 640],
format="jpg",
maptype="roadmap",
markers=markers,
path="color:0x0000ff|weight:2|" + "|".join(waypoints))

Conclusion

Resources and tutorials for python, data science and automation solutions

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store