Fundamentals 12 min read

Using Folium for Interactive Map Visualization in Python

This article introduces the Python library Folium, explains its installation, demonstrates basic map creation, marker and shape addition, and presents a practical case of visualizing parking lot geolocation data with interactive features and clustering, providing code snippets and usage guidance.

IT Services Circle
IT Services Circle
IT Services Circle
Using Folium for Interactive Map Visualization in Python

Previously we introduced several Python visualization modules, but they are limited for geographic visualizations. This guide shows how to create more refined and interactive maps using the folium library, which builds on Python's data handling and Leaflet.js mapping capabilities.

1. Folium Overview and Installation

Folium combines Python's data‑wrangling power with Leaflet.js to render maps directly from Python. Compared with domestic solutions like pyecharts, Folium offers greater flexibility, custom region drawing, and diverse presentation styles.

pip install folium -i http://pypi.douban.com/simple --trusted-host pypi.douban.com

The command uses the domestic Douban mirror for faster installation.

2. Basic Usage

The main class for displaying a map is folium.Map . Its signature is:

class folium.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)

Key parameters include:

location: latitude and longitude as a list or tuple.

zoom_start: initial zoom level (default 10).

control_scale: whether to show a scale bar.

tiles: map style, default "OpenStreetMap".

crs: coordinate reference system, default "EPSG3857".

2.1 Different Map Levels

World Map

import folium
print(folium.__version__)
world_map = folium.Map()
world_map.save('test_01.html')

Generates a global map saved as test_01.html .

Country Map

import folium
national_map = folium.Map(location=[35.3, 100.6], zoom_start=4)
national_map.save('test_02.html')

City Map (example: Beijing)

import folium
city_map = folium.Map(location=[39.93, 116.40], zoom_start=10)
city_map.save('test_03.html')

2.2 Adding Markers

Standard Markers

import folium
bj_map = folium.Map(location=[39.93, 115.40], zoom_start=12, tiles='Stamen Terrain')
folium.Marker(
    location=[39.95, 115.33],
    popup='Mt. Hood Meadows',
    icon=folium.Icon(icon='cloud')
).add_to(bj_map)
folium.Marker(
    location=[39.96, 115.32],
    popup='Timberline Lodge',
    icon=folium.Icon(color='green')
).add_to(bj_map)
folium.Marker(
    location=[39.93, 115.34],
    popup='Some Other Location',
    icon=folium.Icon(color='red', icon='info-sign')
).add_to(bj_map)
bj_map.save('test_04.html')

Circle and CircleMarker

import folium
bj_map = folium.Map(location=[39.93, 116.40], zoom_start=12, tiles='Stamen Toner')
folium.Circle(
    radius=200,
    location=(39.92, 116.43),
    popup='The Waterfront',
    color='#00FFFF',
    fill=False
).add_to(bj_map)
folium.CircleMarker(
    location=(39.93, 116.38),
    radius=50,
    popup='Laurelhurst Park',
    color='#FF1493',
    fill=True,
    fill_color='#FFD700'
).add_to(bj_map)
bj_map.save('test_05.html')

Dynamic Tagging

import folium
dynamic_tagging = folium.Map(
    location=[46.8527, -121.7649],
    tiles='Stamen Terrain',
    zoom_start=13
)
folium.Marker(
    [46.8354, -121.7325],
    popup='Camp Muir'
).add_to(dynamic_tagging)

dynamic_tagging.add_child(folium.ClickForMarker(popup='Waypoint'))

dynamic_tagging.save('test_06.html')

3. Practical Case: Visualizing Parking Lot Locations

3.1 Acquiring Latitude/Longitude Data

Parking data is fetched via a web request and saved to parkings.csv :

# Data source: http://219.136.133.163:8000/Pages/Commonpage/login.aspx
import requests, csv, json, logging
headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
url = 'http://219.136.133.163:8000/Pages/Commonpage/AsyGetData.asmx/GetParkList'
s = requests.session()
s.get(url, headers=headers)
for i in range(1, 318):
    data = {'cp': str(i), 'ps': '10', 'kw': '', 'lon': 'undefined', 'lat': 'undefined', 'type': 'undefined'}
    res = s.post(url, data=data, headers=headers)
    res.encoding = 'utf-8'
    result = json.loads(res.text)['Result']
    for j in result:
        park_name = j['ParkName']
        Lon = j['Longitude']
        Lat = j['Latitude']
        with open('parkings.csv', 'a+', newline='', encoding='gb18030') as f:
            f_csv = csv.writer(f)
            f_csv.writerow([park_name, Lon, Lat])
            logging.info([park_name, Lon, Lat])

The script collects 3,170 parking locations.

3.2 Visualizing with Folium

Load the CSV and plot each point as a CircleMarker :

import pandas as pd, folium

data = pd.read_csv('parkings.csv', encoding='gbk')
park_map = folium.Map(location=[data['latitude'].mean(), data['longitude'].mean()], zoom_start=10, control_scale=True)
incidents = folium.map.FeatureGroup()
for name, row in data.iterrows():
    incidents.add_child(
        folium.CircleMarker(
            (row['latitude'], row['longitude']),
            radius=7,
            color='#FF1493',
            fill=True,
            fill_color='#00FF00',
            fill_opacity=0.4
        )
    )
park_map.add_child(incidents)
park_map.save('park_map1.html')

To avoid clutter, a marker cluster is used:

import pandas as pd, folium
from folium import plugins

data = pd.read_csv('parkings.csv', encoding='gbk')
park_map = folium.Map(location=[data['latitude'].mean(), data['longitude'].mean()], zoom_start=10, control_scale=True)
marker_cluster = plugins.MarkerCluster().add_to(park_map)
for name, row in data.iterrows():
    folium.Marker(location=[row['latitude'], row['longitude']]).add_to(marker_cluster)
park_map.save('park_map2.html')

These maps allow interactive exploration of parking distribution, with zoom‑in revealing individual locations.

References

[1] "Python绘制地图神器folium入门" – https://blog.csdn.net/weixin_38169413/article/details/104806257

[2] Folium quickstart – http://python-visualization.github.io/folium/quickstart.html

pythonmappingData Visualizationgeospatial visualizationWeb Mappingfolium
IT Services Circle
Written by

IT Services Circle

Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.