Skip to main content

Making a Geographic Heatmap with Python

     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 pands (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 HeatMapmap_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 webdriverfn='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()

Comments

  1. in above code "folium.GeoJson(district23).add_to(hmap)" written for creating heatmap.
    what it defines code? i have five columns sample data with columns name,latitude,longitude. i written with the help of above code i struck on that code..pls help me on this issue .with out this line(folium.GeoJson(district23).add_to(hmap)
    ) i run but i am not getting map and it is not shown error, but not getting map

    ReplyDelete
  2. Name latitude longitude
    Ram 30.02096 -95.52322
    Venkat 30.27043056 -97.75386111
    Vijay 30.2452 -97.75751
    Nitesh 30.29370998 -97.74172805
    Chinna 30.26416385 -97.74061482
    Prakash 30.268975 -97.72871389
    this is my sample data

    import pandas as pd
    import folium
    from folium.plugins import HeatMap

    df = pd.read_csv(r'C:\Users\Ramu\Desktop\python csv.csv')

    hmap = folium.Map(location=[30.169621,-96.683617], zoom_start=8,)

    hm_wide = HeatMap(
    list(zip(df.latitude.values, df.longitude.values)),

    min_opacity=0.3,
    radius=15,
    blur=10,
    max_zoom=2,
    )
    folium.Geocsv(latitude).add_to(hmap)
    hmap.add_child(hm_wide)

    if i run this code i am getting error-

    ===================== RESTART: C:\Users\Ramu\Desktop\new.py ====================
    Traceback (most recent call last):
    File "C:\Users\Ramu\Desktop\new.py", line 20, in
    folium.Geocsv(latitude).add_to(hmap)
    AttributeError: module 'folium' has no attribute 'Geocsv'

    without this line code "folium.Geocsv(latitude).add_to(hmap)" i am not getting any error but map was not shown...
    please help me on this issue, it is very important for me.
    thanks

    ReplyDelete

Post a Comment

Popular posts from this blog

MQTT set up Flask

 MQTT Introduction: It is message broker which holds the data when ever a consumer will connected to the topic then he will receive the data . mqtt is a machine to machine message broker, mainly used in IOT application, the default port is 1883   Installation: sudo apt-get update sudo apt-get install mosquitto Command line execution: Producer mosquitto_pub -h 127.0.0.1 -t 'topic_name' -m '{'name':'Sony'}' Subscriber mosquitto_sub -h 127.0.0.1 -t 'topic_name' -h : it is the host address -t : topic name -m : message payload QOS in MQTT: QOS(quality of services) there are mainly 3 services are available in mqtt  qos=0 qos=1 qos=2 QOS (0,0): At most once service, publisher will send a message to broker at most once, the broker passes a message to subscriber one time     

CommandLine Args In Python

 Command line args in Python :      When the program comes to Python , it's all about libraries .Argparser is the library used for the taking inputs from the command line. Here you can validate the arguments which are entered by the user without writing the another function to validate from the if conditions. suppose give a filename like cmdprocess.py You can give the expecting arguments like below cmdprocess.py --help      it will give the total arguments with respective commands to represent Required =True :           When the required is true. You have to enter the argument.   Type = function name:          Type is very useful to validate the input entered by the user. so that you can send a message like user need to enter the defined arguments only. This function always expects the input argument . Custom-Exceptions In Python:    There are multiple exception...