Basically I am using openweathermap
API to capture the location coordinates of From place
and To place
. Thereafter, using mapbox
API, I capture the route. To highlight the route, again we need coordinates to join them all as a line.
def get_location(name):
name = name.lower()
url = 'http://api.openweathermap.org/data/2.5/weather?q='+str(name)+'&appid='+str(<your_openweathermap_api>)
open_url = urllib2.urlopen(url)
open_w = json.load(open_url)
ll = [i[1] for i in open_w['coord'].items()]
lat = ll[0]
lon = ll[1]
return lat, lon
def map_locations(home, dest):
initial_lat, initial_lon = get_location(home)
final_lat, final_lon = get_location(dest)
return initial_lat, initial_lon, final_lat, final_lon
We make use of the above functions to capture the coordinates of From
and To
.
To capture the coordinates of the route path, we need to use of mapbox
API.
def get_route(home, dest, travelling_mode):
initial_lat, initial_lon, final_lat, final_lon = map_locations(home, dest)
mapurl = 'https://api.mapbox.com/directions/v5/mapbox/' + str(travelling_mode) + '/' + str(initial_lon) + ',' + str(initial_lat) + ';' + str(final_lon) + ',' + str(final_lat) + '?geometries=geojson&access_token=' + str(<your_mapbox_api>)
openmap = urllib2.urlopen(mapurl)
mapjs = json.load(openmap)
lons = []
lats = []
for ks in mapjs['routes']:
for k, v in ks.items():
if k == 'geometry':
for eachk, eachv in v.items():
if eachk == 'coordinates':
for eachloc in eachv:
lons.append(eachloc[0])
lats.append(eachloc[1])
return lats, lons
# print(get_route('hyderabad', 'chennai', 'driving'))
And finally we have to plot them all.
lats, lons = get_route(`home`, `dest`, `travelling_mode`)
go.Scattermapbox(
lat=lats,
lon=lons,
mode='lines',
line=dict(width=2),
marker=dict(
size=5,
),
text='{} to {} : {}'.format(str(`home`).title(), str(`dest`).title(), str(`travelling_mode`).title()),
hoverinfo='text'
)
MapBox
provides 3 types of traveling mode - Driving
, Cycling
and Walking
. Make sure to have the api keys
to get the data.
Hope this will solve your issue.