Creating Interactive Maps Using Python's Folium Library
Tags: python, beginners, json
Published: 2020-10-21 18:48:41

 Python's Folium library is build on Leaflet.js which is used for building interactive maps.

In this section we will try to build an interactive map where you can view different apartments in different buildings/townships for sale and their details. We can also search based on ward_name.

![Bangalore-photo](https://dev-to-uploads.s3.amazonaws.com/i/s9dn2doa6dwqlv7rxo6x.JPG)
 

### **Prerequisites**

* Python and Pip/Conda installed.
* Basics of Python.
* Any IDE installed, I would recommend using Jupyter Notebook.

So let's get started ...

Before starting, download all the files necessary from my repository (link is given in the end)

### __Part One__: Installing Folium and Pandas

 If you are using Jupyter notebook you can simply type and run:
 
~~~
pip install pandas, folium=="0.8.0"
~~~
Or else you can go to the terminal and run the same command.

### __Part Two__: Importing Libraries

For implementing this project, we would be required to import following python libraries :
* pandas: For CSV data import and processing
* os: For accessing JSON file
* folium: For building interactive maps 
* folium.plugins: For using leaflet external plugins

~~~
import os
import pandas as pd
import folium.plugins as plugins
import folium
~~~

### __Part Three__: Data Import And Processing

In order to use data, we need to first import them and do some processing.
We have two datasets indiviual_apartments.csv and buildings.csv.

1.  individual_apartments.csv: This dataset gives you details about the individual apartments and their details like price, area, unit type.

To import this dataset and display top 5 rows :

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0j5q1kizfgao874kr2gk.JPG)

2. buildings.csv: Buildings.csv have details of different buildings and their locations. Repeat the same steps as above, and you would find four columns i.e names, lat, lon, and geometry. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/nyg5x3os36k7eocoeyol.JPG)

But there are the problem's with this dataset: 
* Folium cannot directly use the Geometry column.
* There is no need for separate lat, lon columns.

What we can do is delete the geometry column, combine lat, lon into one new column and then delete them as well.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rei60unmj6q0plt23usk.JPG)

### __Part Four__: Building interactive maps 

#### 1. Load basic map of Bangalore city: 
We can create the map of bangalore city using folium's Map function. The map function according to documentation looks like this : 
~~~
Map(location=None, width='100%', height='100%', left='0%', top='0%', position='relative', tiles='OpenStreetMap', attr=None, min_zoom=0, max_zoom=18, zoom_start=10, min_lat=- 90, max_lat=90, min_lon=- 180, max_lon=180, max_bounds=False, crs='EPSG3857', control_scale=False, prefer_canvas=False, no_touch=False, disable_3d=False, png_enabled=False, zoom_control=True, **kwargs)
~~~

Out of this only we would only use location, zoom_start and max_zoom :
1. The location takes None by default or a list or a tuple which consists of latitude and longitude. We would pass a tuple consisting of latitude and longitude of Bangalore city : (12.9716, 77.5946)
2. The zoom_start takes a None by default or integer which is the initial zoom_level of the map.
3. The max_zoom takes a None by default or an integer which is the max_zoom level of the map.

![capture_3](https://dev-to-uploads.s3.amazonaws.com/i/ndtvxons7ichvs6o1gqz.JPG)
 
#### 2. Add GeoJSON layer: 
GeoJSON layer helps us to differentiate bangalore city into different wards. The JSON layer we used has coordinates and dimensions of different wards along with few other details. We also add a GeoJsonToolTip which basically allows to hover over wards and get their ward_name and ward_no. 

To load the JSON file we use the os.path module. 

![geojson](https://dev-to-uploads.s3.amazonaws.com/i/cm7gxml2o0jss72mfmn7.JPG)

#### 3. Add a search button based on geoJSON layer : 
folium.plugin has a seacrch tool that can be implemented on the basis of geoJSON layer. We can specifiy the search label i.e on which label of geoJSON basis we can add the search. We would be implementing search based on ward_name. You can also try implementing search functionalities based on other labels. Ex: Ward_no. 
Since our wards are of shape polygon, have to specify that also in the search. (refer bbmp.json file)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/w0b7gzz49k7cli9ubr4k.JPG)

#### 3. Add popups and fill in details : The dataset of indiviual_apartments.csv contains large number of rows. So for simplification we only used 1300 rows. 

What we want to do shows popups of buildings and on each popup it shows different apartments which are on sale and their details.

Follow these steps : 
* Iterate through rows of buildings dataset from 0 to 1300.
* For building name on popup we create an html text.
* For a table on popup we filter out all rows with the name of building equal to current building of indiviual_apartments dataset.
* Create a popup data combining both of these.
* Add a marker to the map on the location given in location Tabl.

The output would look like this :

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/s1tlgagsi46ah7tccpnh.JPG)

But the map now looks a little overpopulated with markers. What we can do cluster these markers using folium plugin Marker Cluster.

We just need to create markercluster object and add all these markers in these markercluster. And finally add these markercluster objects to the map.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2meikbgcxgz8fzde38wf.JPG)

#### 4. Final Step to download the file : 
Before finalling downloading the map, you can add a control on layer using layercontrol. It gives users an option to disable or enable the geoJSON layer.

Then you can download the map using .save() method with the filename and its extension inside. ex: "bangalore_project.html"

## References : 
* https://github.com/PrakharKopergaonkar/Bangalore-apartments
* https://python-visualization.github.io/folium/
* https://python-visualization.github.io/folium/plugins.html