Displaying Locations using Heatmap

by Kardi Teknomo

In previous tutorial in Automatic Geocoding, you have learn how to geocode street and location into longitude and latitude coordinate. In this tutoial, we will use plot the geocoded locations into a heatmap.

For this tutorial, I have geocoded the first 250 rows out of almost a million rows of Metro Manila spatial traffic accident data that is publicly available in GitHub. For your own purpose, you may want to change the data, using the same format of the name of variables.

Installation

To use the code in this tutorial, I assume you have installed gmaps:

conda install -c conda-forge gmaps

If the heatmap is not displayed in Jupyter, try the following commands in command prompt of anaconda:

jupyter nbextension enable --py --sys-prefix widgetsnbextension

or

jupyter nbextension enable --py widgetsnbextension

and

jupyter nbextension enable --py gmaps

Another possible problem if your map is not displayed is because you did not activate your API_KEY. (you can deetct this problem using Chrome Developer Tools - Console and you can see the error related to the Google Map key). In this case, go to Google Developer page, select the proper API (Google Maps JavaScript API, Google Maps Static API, Google Maps Geolocation API) and set to enable.

Module gmaps is still using Google Map API and you can use the same API_KEY as in Geocode. Just in case you have accessed the geocoded locations without using the Google Map API, then you need to sign up to Google Map to get the API_KEY.

Once we have the API_KEY, we can import the necessary modules and set up GoogleMap client object.

In [10]:
import pandas as pd
import googlemaps
import gmaps

API_KEY = 'AI....'
gm = googlemaps.Client(key=API_KEY)
gmaps.configure(api_key=API_KEY) # Your Google API key

Geocoded Location Data

If you don't have the geocoded location data, please read my previous tutorial on Automatic Geocoding before you read this tutorial.

Suppose you have already the clean-geocoded location data. Then we read the location data into pandas dataframe. We separate the location from the weight. The weight represents how frequent the event (in this case, accident events) happened in one place.

In [19]:
df=pd.read_csv('locations.csv', low_memory=False, index_col = 'key')  # read geocoded location from file
locations = df[['latitude', 'longitude']]          # put latitide and longitude as a variable name 'locations'
val = df['weight']                                 # put the weight into variable name 'val'
df.head()                                          # display the first 5 rows of the location data
Out[19]:
latitude longitude weight
key
0 14.490669 121.053920 1
1 14.547370 121.026641 1
2 14.690876 121.090476 1
4 14.464852 120.984819 1
5 14.605992 121.028052 1

Getting the Center of the Map

To display the map properly, we need to define the center of the city. Since the location data was from Metro Manila, we specify that city in here. If you use your own city of interest, just change the name of the city.

In [20]:
# do geocode for the whole mega city
geocode_result = gm.geocode('Metro Manila')[0]  # change the name into your city of interest

# get the center of the city
center_lat=geocode_result['geometry']['location']['lat']
center_lng=geocode_result['geometry']['location']['lng']
print('center=',center_lat,center_lng)
center= 14.6090537 121.0222565

Drawing HeatMap

We want to display the geocoded location into heatmap. To draw a heat map, I created the following function.

In [17]:
def drawHeatMap(location, val, zoom, intensity, radius):
    # setting the data and parameters
    heatmap_layer = gmaps.heatmap_layer(locations, val, dissipating = True)
    heatmap_layer.max_intensity = intensity
    heatmap_layer.point_radius = radius
    # draw the heatmap into a figure
    fig = gmaps.figure()
    fig = gmaps.figure(center = [center_lat,center_lng], zoom_level=zoom)
    fig.add_layer(heatmap_layer)
    return fig

To call the function above, set up the parameters and call the function to draw the heatmap. You can experiment with different parameter values. The result map can also be saved as PNG file.

In [25]:
# set up parameters
zoom=10
intensity=5
radius=15

# call the function to draw the heatmap
drawHeatMap(locations, val, zoom, intensity, radius)
heatmap

last update: September 2017

Cite this tutorial as: Teknomo, K. (2017) Displaying Locations using Heatmap (http://people.revoledu.com/kardi/tutorial/Python/)

See Also:

Visit www.Revoledu.com for more tutorials in Data Science

Copyright © 2017 Kardi Teknomo

Permission is granted to share this notebook as long as the copyright notice is intact.