Making a Geographic Heatmap with Python

Making a Geographic Heatmap with Python

1*WzWo_ORjyPOavIdMJrahYg.png

We have a requirement like need to create a map where user is traveled.There are many libraries available in python to draw a map if you have list of co-ordinates with you like(longitude and latitude)

To name few packages : vincent, bokeh, plot.ly and matplotlib and folium

Things to consider while choosing the library:

  1. Open source

  2. Painless to use

  3. built in support for heat-maps

  4. actively maintained

Folium is the lib which will satisfy above all use cases

Requirements:


pip install folium

pip install geopands (for adding other geo json files)

pip install pandas (to read csv of excel files which are having the co-ordinates data)

Creating the map:


import pandas as pd 
import folium
from folium.plugins import HeatMap
map_df = pd.read_csv('map.csv', sep='\t')
max_amount = float(map_df['Amount'].max())
hmap = folium.Map(location=[42.5, -75.5], zoom_start=7, )
hm_wide = HeatMap( list(zip(map_df.lat.values, 
            map_df.lon.values, map_df.Amount.values)),
                   min_opacity=0.2,
                   max_val=max_amount,
                   radius=17, blur=15, 
                   max_zoom=1, 
                 )
folium.GeoJson(district23).add_to(hmap)
hmap.add_child(hm_wide)

Save map as html:

 hmap.save(os.path.join('results', 'map.html'))

Export it as PNG/JPEG:

  1. Using with xvfb with cutycapt

  2. Using Selenium web driver

Cutycapt:


    Install the package using the apt-get cutycapt

    sudo apt-get install cutycapt

    sudo apt-get install xvfb

Python code:


import os
    import subprocess
    outdir = "screenshots" # this directory has to exist..
    map.save("tmp.html")
    url = "file://{}/tmp.html".format(os.getcwd())
    outfn = os.path.join(outdir,"outfig.png")
    subprocess.check_call(["cutycapt","--url={}".format(url), "--out={}".format(outfn)])

Selenium Webdriver:


import os
import time
from selenium import webdriver
fn='testmap.html'
tmpurl='file://{path}/{mapfile}'.format(path=os.getcwd(),mapfile=fn)
folium_map.save(fn)
browser = webdriver.Firefox()
browser.get(tmpurl)
time.sleep(5)  #Give the map tiles some time to load
browser.save_screenshot('map.png')
browser.quit()