Make beautiful maps with Leaflet.js & Python
—
Extensive plugin ecosystem providing specialized functionality including clustering, heatmaps, drawing tools, temporal visualizations, advanced controls, and interactive features. All plugins extend the base folium functionality with additional Leaflet.js plugins.
Plugins for efficiently handling large numbers of markers and managing marker overlaps.
class MarkerCluster:
"""
Group nearby markers into clusters for better performance and visualization.
Parameters:
- locations: list, marker coordinates (optional, can add markers individually)
- popups: list, popup content for each marker (optional)
- tooltips: list, tooltip content for each marker (optional)
- icons: list, custom icons for each marker (optional)
- name: str, layer name for layer control
- overlay: bool, treat as overlay layer (default True)
- control: bool, show in layer control (default True)
- show: bool, show layer initially (default True)
- icon_create_function: str, JavaScript function for custom cluster icons
- options: dict, additional clustering options
Returns:
MarkerCluster instance
"""
def __init__(
self,
locations=None,
popups=None,
tooltips=None,
icons=None,
name=None,
overlay=True,
control=True,
show=True,
icon_create_function=None,
options=None
): ...
class FastMarkerCluster:
"""
High-performance clustering for very large marker datasets.
Parameters:
- data: list, marker data with coordinates and properties
- name: str, layer name for layer control
- callback: str, JavaScript callback function for marker creation
- options: dict, clustering configuration options
Returns:
FastMarkerCluster instance
"""
def __init__(
self,
data,
name=None,
callback=None,
options=None
): ...
class OverlappingMarkerSpiderfier:
"""
Separate overlapping markers in a spider/fan pattern when clicked.
Parameters:
- name: str, layer name
- overlay: bool, treat as overlay (default True)
- control: bool, show in layer control (default True)
- show: bool, show initially (default True)
Returns:
OverlappingMarkerSpiderfier instance
"""
def __init__(
self,
name=None,
overlay=True,
control=True,
show=True
): ...Plugins for visualizing point density and temporal patterns.
class HeatMap:
"""
Create density heatmaps from point data.
Parameters:
- data: list, point data [[lat, lon, intensity], ...] or [[lat, lon], ...]
- name: str, layer name for layer control
- min_opacity: float, minimum opacity (default 0.4)
- max_zoom: int, maximum zoom level (default 18)
- max_val: float, maximum data value for scaling (default 1.0)
- radius: int, heat radius in pixels (default 25)
- blur: int, blur amount (default 15)
- gradient: dict, color gradient mapping {value: 'color'}
- overlay: bool, treat as overlay layer (default True)
- control: bool, show in layer control (default True)
- show: bool, show layer initially (default True)
Returns:
HeatMap instance
"""
def __init__(
self,
data,
name=None,
min_opacity=0.4,
max_zoom=18,
max_val=1.0,
radius=25,
blur=15,
gradient=None,
overlay=True,
control=True,
show=True
): ...
class HeatMapWithTime:
"""
Create animated heatmaps showing temporal patterns.
Parameters:
- data: list, time-series data with timestamps
- name: str, layer name
- index: list, time index labels
- auto_play: bool, start animation automatically (default False)
- display_index: bool, show time index (default True)
- overlay: bool, treat as overlay (default True)
- control: bool, show in layer control (default True)
- show: bool, show initially (default True)
Returns:
HeatMapWithTime instance
"""
def __init__(
self,
data,
name=None,
index=None,
auto_play=False,
display_index=True,
overlay=True,
control=True,
show=True,
**kwargs
): ...Interactive tools for creating and editing geometries directly on the map.
class Draw:
"""
Interactive drawing tools for creating and editing geometries.
Parameters:
- export: bool, enable GeoJSON export (default False)
- filename: str, export filename (default 'data.geojson')
- position: str, control position (default 'topleft')
- draw_options: dict, drawing tool options
- edit_options: dict, editing tool options
Returns:
Draw instance
"""
def __init__(
self,
export=False,
filename='data.geojson',
position='topleft',
draw_options=None,
edit_options=None
): ...
class GeoMan:
"""
Advanced geometry management and editing tools.
Parameters:
- position: str, control position (default 'topleft')
- draw_circle_marker: bool, enable circle marker drawing (default True)
- draw_polyline: bool, enable polyline drawing (default True)
- draw_rectangle: bool, enable rectangle drawing (default True)
- draw_polygon: bool, enable polygon drawing (default True)
- draw_circle: bool, enable circle drawing (default True)
- draw_marker: bool, enable marker drawing (default True)
- edit_mode: bool, enable editing mode (default True)
- drag_mode: bool, enable drag mode (default True)
- cut_polygon: bool, enable polygon cutting (default True)
- removal_mode: bool, enable removal mode (default True)
Returns:
GeoMan instance
"""
def __init__(
self,
position='topleft',
draw_circle_marker=True,
draw_polyline=True,
draw_rectangle=True,
draw_polygon=True,
draw_circle=True,
draw_marker=True,
edit_mode=True,
drag_mode=True,
cut_polygon=True,
removal_mode=True
): ...
class MeasureControl:
"""
Tool for measuring distances and areas on the map.
Parameters:
- position: str, control position (default 'topright')
- primary_length_unit: str, primary length unit ('feet', 'meters', 'miles', 'kilometers')
- secondary_length_unit: str, secondary length unit
- primary_area_unit: str, primary area unit ('sqfeet', 'sqmeters', 'sqmiles', 'hectares', 'acres', 'sqkilometers')
- secondary_area_unit: str, secondary area unit
- active_color: str, active measurement color (default '#ABE67E')
- completed_color: str, completed measurement color (default '#C8F2BE')
Returns:
MeasureControl instance
"""
def __init__(
self,
position='topright',
primary_length_unit='meters',
secondary_length_unit=None,
primary_area_unit='sqmeters',
secondary_area_unit=None,
active_color='#ABE67E',
completed_color='#C8F2BE'
): ...Enhanced layer management with grouping and tree structures.
class GroupedLayerControl:
"""
Layer control with hierarchical grouping of layers.
Parameters:
- groups: dict, layer groups with names and layers
- position: str, control position (default 'topright')
- collapsed: bool, collapse control initially (default True)
- exclusive_groups: list, groups where only one layer can be active
Returns:
GroupedLayerControl instance
"""
def __init__(
self,
groups=None,
position='topright',
collapsed=True,
exclusive_groups=None
): ...
class TreeLayerControl:
"""
Tree-structured layer management interface.
Parameters:
- base_tree: dict, base layer hierarchy
- overlay_tree: dict, overlay layer hierarchy
- position: str, control position (default 'topright')
- closed_symbol: str, symbol for closed nodes (default '+')
- open_symbol: str, symbol for open nodes (default '-')
- space_symbol: str, spacing symbol (default ' ')
- selector_back: bool, enable selector background (default False)
- selection_weight: int, selection highlight weight (default 1)
- collapsed: bool, collapse initially (default True)
Returns:
TreeLayerControl instance
"""
def __init__(
self,
base_tree=None,
overlay_tree=None,
position='topright',
closed_symbol='+',
open_symbol='-',
space_symbol=' ',
selector_back=False,
selection_weight=1,
collapsed=True
): ...
class FeatureGroupSubGroup:
"""
Create nested feature groups for advanced layer organization.
Parameters:
- group: FeatureGroup, parent feature group
- name: str, subgroup name
- overlay: bool, treat as overlay (default True)
- control: bool, show in layer control (default True)
- show: bool, show initially (default True)
Returns:
FeatureGroupSubGroup instance
"""
def __init__(
self,
group,
name=None,
overlay=True,
control=True,
show=True
): ...Plugins that enhance map navigation and user interface.
class Fullscreen:
"""
Add fullscreen toggle functionality to the map.
Parameters:
- position: str, control position (default 'topleft')
- title: str, button title text (default 'Full Screen')
- title_cancel: str, cancel button title (default 'Exit Full Screen')
- force_separate_button: bool, force separate button (default False)
Returns:
Fullscreen instance
"""
def __init__(
self,
position='topleft',
title='Full Screen',
title_cancel='Exit Full Screen',
force_separate_button=False
): ...
class MiniMap:
"""
Add an overview minimap widget to the main map.
Parameters:
- tile_layer: TileLayer, tile layer for minimap (defaults to main map tiles)
- position: str, minimap position (default 'bottomright')
- width: int, minimap width in pixels (default 150)
- height: int, minimap height in pixels (default 150)
- collapsed_width: int, collapsed width (default 19)
- collapsed_height: int, collapsed height (default 19)
- zoom_level_offset: int, zoom offset relative to main map (default -5)
- zoom_animation: bool, enable zoom animation (default False)
- toggle_display: bool, allow minimap toggle (default False)
- auto_toggle_display: bool, auto-toggle based on main map zoom (default False)
- minimized: bool, start minimized (default False)
Returns:
MiniMap instance
"""
def __init__(
self,
tile_layer=None,
position='bottomright',
width=150,
height=150,
collapsed_width=19,
collapsed_height=19,
zoom_level_offset=-5,
zoom_animation=False,
toggle_display=False,
auto_toggle_display=False,
minimized=False
): ...
class MousePosition:
"""
Display current mouse cursor coordinates on the map.
Parameters:
- position: str, control position (default 'bottomright')
- separator: str, coordinate separator (default ' | ')
- empty_string: str, text when outside map bounds (default 'Unavailable')
- lng_first: bool, show longitude first (default False)
- num_digits: int, decimal places for coordinates (default 5)
- prefix: str, prefix text
- lat_formatter: callable, custom latitude formatter
- lng_formatter: callable, custom longitude formatter
Returns:
MousePosition instance
"""
def __init__(
self,
position='bottomright',
separator=' | ',
empty_string='Unavailable',
lng_first=False,
num_digits=5,
prefix='',
lat_formatter=None,
lng_formatter=None
): ...
class LocateControl:
"""
Add user location finding control to the map.
Parameters:
- position: str, control position (default 'topleft')
- auto_start: bool, start location tracking automatically (default False)
- set_view: bool or str, set map view to user location (default 'untilPanOrZoom')
- keep_current_zoom_level: bool, maintain current zoom when locating (default True)
- strings: dict, localized text strings
- locateOptions: dict, location options (accuracy, timeout, etc.)
Returns:
LocateControl instance
"""
def __init__(
self,
position='topleft',
auto_start=False,
set_view='untilPanOrZoom',
keep_current_zoom_level=True,
strings=None,
locateOptions=None
): ...
class ScrollZoomToggler:
"""
Toggle scroll wheel zoom functionality.
Parameters:
- position: str, control position (default 'topright')
Returns:
ScrollZoomToggler instance
"""
def __init__(self, position='topright'): ...Plugins for time-based data visualization and animation.
class TimestampedGeoJson:
"""
Display animated GeoJSON features over time.
Parameters:
- data: dict, GeoJSON FeatureCollection with time properties
- period: str, time period format ('P1D' for daily, 'P1M' for monthly, etc.)
- add_last_point: bool, keep last point visible (default True)
- auto_play: bool, start animation automatically (default False)
- loop: bool, loop animation (default True)
- max_speed: int, maximum animation speed (default 10)
- loop_button: bool, show loop toggle button (default False)
- date_options: dict, date formatting options
- time_slider_drag_update: bool, update during drag (default False)
- duration: str, feature duration on map
Returns:
TimestampedGeoJson instance
"""
def __init__(
self,
data,
period='P1D',
add_last_point=True,
auto_play=False,
loop=True,
max_speed=10,
loop_button=False,
date_options=None,
time_slider_drag_update=False,
duration=None,
**kwargs
): ...
class TimeSliderChoropleth:
"""
Create animated choropleth maps with time slider control.
Parameters:
- data: DataFrame, time-series data for choropleth
- styledict: dict, styling configuration for time periods
- name: str, layer name
- overlay: bool, treat as overlay (default False)
- control: bool, show in layer control (default True)
- show: bool, show initially (default True)
Returns:
TimeSliderChoropleth instance
"""
def __init__(
self,
data,
styledict=None,
name=None,
overlay=False,
control=True,
show=True
): ...
class Timeline:
"""
Create timeline visualization for temporal events.
Parameters:
- data: dict, timeline data with events and timestamps
- name: str, layer name
- overlay: bool, treat as overlay (default True)
- control: bool, show in layer control (default True)
- show: bool, show initially (default True)
Returns:
Timeline instance
"""
def __init__(
self,
data,
name=None,
overlay=True,
control=True,
show=True
): ...
class TimelineSlider:
"""
Create slider control for timeline navigation.
Parameters:
- data: dict, timeline data
- start: int, start position (default 0)
- end: int, end position
- step: int, step size (default 1)
- position: str, control position (default 'bottomleft')
Returns:
TimelineSlider instance
"""
def __init__(
self,
data,
start=0,
end=None,
step=1,
position='bottomleft'
): ...
class TimestampedWmsTileLayers:
"""
Creates time-enabled WMS tile layers with temporal controls.
Adds time dimension support to WMS tile layers using the Leaflet.TimeDimension plugin,
enabling temporal data visualization and animation controls.
Parameters:
- data: WmsTileLayer or list of WmsTileLayer, WMS layers to add time support to
- transition_time: int, duration in ms of transition between timestamps (default 200)
- loop: bool, whether animation loops (default False)
- auto_play: bool, whether animation starts automatically (default False)
- period: str, ISO8601 duration for time intervals (default 'P1D')
- time_interval: bool, time interval settings (default False)
Returns:
TimestampedWmsTileLayers instance
"""
def __init__(
self,
data,
transition_time=200,
loop=False,
auto_play=False,
period='P1D',
time_interval=False
): ...
class Realtime:
"""
Real-time data updates and streaming visualization.
Parameters:
- source: str or callable, data source URL or function
- start: bool, start updates immediately (default True)
- interval: int, update interval in milliseconds (default 60000)
- get_feature_id: callable, function to get feature ID
- update_feature: callable, function to update features
- remove_missing: bool, remove missing features (default False)
- container: dict, GeoJSON container for features
Returns:
Realtime instance
"""
def __init__(
self,
source,
start=True,
interval=60000,
get_feature_id=None,
update_feature=None,
remove_missing=False,
container=None
): ...Plugins for searching map features and location geocoding.
class Search:
"""
Add search functionality for map features.
Parameters:
- layer: Layer, layer to search within
- search: list or str, searchable properties or search function
- position: str, control position (default 'topleft')
- placeholder: str, search input placeholder text
- collapsed: bool, start collapsed (default True)
- search_label: str, search field label
- search_zoom: int, zoom level for search results
- move_to_location: bool, move map to search result (default True)
Returns:
Search instance
"""
def __init__(
self,
layer=None,
search=None,
position='topleft',
placeholder='Search...',
collapsed=True,
search_label='Search',
search_zoom=None,
move_to_location=True,
**kwargs
): ...
class Geocoder:
"""
Add geocoding search control for address lookup.
Parameters:
- position: str, control position (default 'topleft')
- add_marker: bool, add marker for geocoded location (default True)
- collapsed: bool, start collapsed (default False)
- placeholder: str, search placeholder text
Returns:
Geocoder instance
"""
def __init__(
self,
position='topleft',
add_marker=True,
collapsed=False,
placeholder='Search for a location...'
): ...Custom marker types and pattern fills for advanced visualization.
class BeautifyIcon:
"""
Create enhanced marker icons with custom styling and effects.
Parameters:
- icon: str, icon name (FontAwesome)
- icon_shape: str, icon shape ('marker', 'circle-dot', 'rectangle', etc.)
- border_width: int, border width (default 3)
- border_color: str, border color (default '#1EB300')
- text_color: str, text/icon color (default 'white')
- background_color: str, background color (default '#1EB300')
- inner_icon_style: str, additional CSS for inner icon
Returns:
BeautifyIcon instance
"""
def __init__(
self,
icon=None,
icon_shape='marker',
border_width=3,
border_color='#1EB300',
text_color='white',
background_color='#1EB300',
inner_icon_style=''
): ...
class BoatMarker:
"""
Create directional boat-shaped markers for tracking moving objects.
Parameters:
- location: tuple, marker coordinates [lat, lon]
- heading: float, direction heading in degrees
- wind_heading: int, wind direction in degrees (default 0)
- wind_speed: int, wind speed (default 0)
- color: str, marker color (default '#d4442e')
Returns:
BoatMarker instance
"""
def __init__(
self,
location,
heading=0,
wind_heading=0,
wind_speed=0,
color='#d4442e'
): ...
class SemiCircle:
"""
Create semi-circular markers for directional data visualization.
Parameters:
- location: tuple, center coordinates [lat, lon]
- radius: float, radius in meters
- direction: float, direction in degrees (0 = North)
- arc: float, arc angle in degrees (default 180)
- popup: str or Popup, popup content
- tooltip: str or Tooltip, tooltip content
- color: str, border color
- weight: int, border width
- fill_color: str, fill color
- fill_opacity: float, fill opacity
Returns:
SemiCircle instance
"""
def __init__(
self,
location,
radius=10,
direction=0,
arc=180,
popup=None,
tooltip=None,
**kwargs
): ...
class CirclePattern:
"""
Create circular pattern fills for polygons.
Parameters:
- color: str, pattern color (default 'black')
- weight: int, pattern line weight (default 1)
- radius: int, circle radius (default 20)
- fill_opacity: float, pattern opacity (default 1.0)
- opacity: float, pattern line opacity (default 1.0)
Returns:
CirclePattern instance
"""
def __init__(
self,
color='black',
weight=1,
radius=20,
fill_opacity=1.0,
opacity=1.0
): ...
class StripePattern:
"""
Create stripe pattern fills for polygons.
Parameters:
- color: str, stripe color (default 'black')
- weight: int, stripe width (default 4)
- space: int, space between stripes (default 4)
- opacity: float, stripe opacity (default 1.0)
- angle: int, stripe angle in degrees (default 45)
Returns:
StripePattern instance
"""
def __init__(
self,
color='black',
weight=4,
space=4,
opacity=1.0,
angle=45
): ...Special effects and animated elements for enhanced visualization.
class AntPath:
"""
Create animated dashed lines with marching ants effect.
Parameters:
- locations: list, path coordinates
- color: str, path color (default 'blue')
- weight: int, path width (default 3)
- opacity: float, path opacity (default 0.6)
- dash_array: list, dash pattern [dash_length, gap_length]
- delay: int, animation delay in milliseconds (default 400)
- pulse_color: str, pulse highlight color
- paused: bool, start animation paused (default False)
- reverse: bool, reverse animation direction (default False)
- hardware_acceleration: bool, use hardware acceleration (default False)
Returns:
AntPath instance
"""
def __init__(
self,
locations,
color='blue',
weight=3,
opacity=0.6,
dash_array=None,
delay=400,
pulse_color=None,
paused=False,
reverse=False,
hardware_acceleration=False,
**kwargs
): ...
class FloatImage:
"""
Create floating image overlays on the map.
Parameters:
- image: str, image URL or base64 data
- bounds: list, image bounds [[south, west], [north, east]]
- opacity: float, image opacity (default 1.0)
- alt: str, alt text for image
- origin: str, coordinate origin ('upper' or 'lower')
Returns:
FloatImage instance
"""
def __init__(
self,
image,
bounds,
opacity=1.0,
alt='',
origin='upper'
): ...
class Terminator:
"""
Display day/night terminator line on the map.
Parameters:
- time: datetime, time for terminator calculation (default: current time)
- resolution: float, line resolution in degrees (default 2.0)
- color: str, terminator line color (default '#CC0000')
- opacity: float, line opacity (default 0.5)
- weight: int, line width (default 2)
- fill_color: str, night side fill color (default '#000055')
- fill_opacity: float, night side opacity (default 0.2)
Returns:
Terminator instance
"""
def __init__(
self,
time=None,
resolution=2.0,
color='#CC0000',
opacity=0.5,
weight=2,
fill_color='#000055',
fill_opacity=0.2
): ...Plugins for specialized data formats and high-performance rendering.
class PolygonFromEncoded:
"""
Create polygons from encoded polyline strings.
Parameters:
- encoded: str, encoded polyline string
- popup: str or Popup, popup content
- tooltip: str or Tooltip, tooltip content
- color: str, polygon border color
- weight: int, border width
- fill_color: str, fill color
- fill_opacity: float, fill opacity
Returns:
PolygonFromEncoded instance
"""
def __init__(
self,
encoded,
popup=None,
tooltip=None,
**kwargs
): ...
class PolyLineFromEncoded:
"""
Create polylines from encoded polyline strings (Google Polyline format).
Parameters:
- encoded: str, encoded polyline string
- popup: str or Popup, popup content
- tooltip: str or Tooltip, tooltip content
- color: str, line color
- weight: int, line width
- opacity: float, line opacity
Returns:
PolyLineFromEncoded instance
"""
def __init__(
self,
encoded,
popup=None,
tooltip=None,
**kwargs
): ...
class VectorGridProtobuf:
"""
High-performance vector tile rendering using Protobuf format.
Parameters:
- url: str, vector tile server URL template
- name: str, layer name
- options: dict, vector tile options
- vector_tile_layer_styles: dict, styling for vector tile layers
Returns:
VectorGridProtobuf instance
"""
def __init__(
self,
url,
name=None,
options=None,
vector_tile_layer_styles=None
): ...Additional utility plugins for specific use cases.
class PolyLineTextPath:
"""
Add text labels that follow polyline paths.
Parameters:
- polyline: PolyLine, polyline to add text to
- text: str, text content
- repeat: bool, repeat text along path (default False)
- center: bool, center text on path (default False)
- below: bool, place text below path (default False)
- offset: int, text offset from path (default 0)
- orientation: str, text orientation ('flip' or 'perpendicular')
- attributes: dict, additional text attributes
Returns:
PolyLineTextPath instance
"""
def __init__(
self,
polyline,
text,
repeat=False,
center=False,
below=False,
offset=0,
orientation=None,
attributes=None
): ...
class PolyLineOffset:
"""
Create offset parallel polylines.
Parameters:
- polyline: PolyLine, original polyline
- offset: float, offset distance in meters
- popup: str or Popup, popup content
- tooltip: str or Tooltip, tooltip content
Returns:
PolyLineOffset instance
"""
def __init__(
self,
polyline,
offset,
popup=None,
tooltip=None,
**kwargs
): ...
class SideBySideLayers:
"""
Split-screen comparison of two layers with draggable divider.
Parameters:
- layer_left: Layer, left side layer
- layer_right: Layer, right side layer
Returns:
SideBySideLayers instance
"""
def __init__(self, layer_left, layer_right): ...
class DualMap:
"""
Create two synchronized maps side by side for comparison.
Parameters:
- location: tuple, initial center coordinates [lat, lon]
- left_layer: Layer, left map base layer
- right_layer: Layer, right map base layer
- zoom_start: int, initial zoom level (default 10)
- **kwargs: additional map parameters
Returns:
DualMap instance containing two synchronized Map objects
"""
def __init__(
self,
location=None,
left_layer=None,
right_layer=None,
zoom_start=10,
**kwargs
): ...
class TagFilterButton:
"""
Filter map features by tags with button interface.
Parameters:
- tags: list, available filter tags
- position: str, control position (default 'topleft')
- clear_text: str, clear filter button text (default 'Clear filter')
- tags_key: str, property key for tags in features (default 'tags')
Returns:
TagFilterButton instance
"""
def __init__(
self,
tags,
position='topleft',
clear_text='Clear filter',
tags_key='tags'
): ...import folium
from folium.plugins import MarkerCluster
import pandas as pd
# Sample data
data = pd.DataFrame({
'lat': [45.52, 45.53, 45.51, 45.54, 45.50],
'lon': [-122.67, -122.66, -122.68, -122.65, -122.69],
'name': ['Point A', 'Point B', 'Point C', 'Point D', 'Point E'],
'value': [10, 25, 15, 30, 5]
})
m = folium.Map(location=[45.52, -122.67], zoom_start=12)
# Create marker cluster
marker_cluster = MarkerCluster(
name='Clustered Points',
overlay=True,
control=True,
icon_create_function="""
function(cluster) {
var markers = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < markers.length; i++) {
sum += markers[i].options.myValue || 0;
}
return L.divIcon({
html: '<div style="background-color:red;border-radius:50%;width:30px;height:30px;display:flex;align-items:center;justify-content:center;color:white;font-weight:bold;">' + sum + '</div>',
className: 'custom-cluster-icon',
iconSize: [30, 30]
});
}
"""
)
# Add markers to cluster
for idx, row in data.iterrows():
folium.Marker(
location=[row['lat'], row['lon']],
popup=f"{row['name']}: {row['value']}",
tooltip=row['name'],
icon=folium.Icon(color='blue', icon='info-sign'),
# Add custom property for cluster calculation
).add_to(marker_cluster)
# Note: Custom properties need to be added via JavaScript
marker_cluster.add_to(m)
folium.LayerControl().add_to(m)
m.save('clustered_markers.html')import folium
from folium.plugins import HeatMapWithTime
import numpy as np
import datetime
# Generate sample time-series data
base_time = datetime.datetime(2023, 1, 1)
times = [base_time + datetime.timedelta(hours=i) for i in range(24)]
# Simulate hourly location data (e.g., taxi pickups)
data_by_hour = []
for hour in range(24):
# Generate random points around city center
n_points = 50 + int(30 * np.sin(hour * np.pi / 12)) # More activity during rush hours
lats = np.random.normal(45.52, 0.01, n_points)
lons = np.random.normal(-122.67, 0.01, n_points)
intensities = np.random.exponential(2, n_points)
hour_data = [[lat, lon, intensity] for lat, lon, intensity in zip(lats, lons, intensities)]
data_by_hour.append(hour_data)
m = folium.Map(location=[45.52, -122.67], zoom_start=13)
# Create animated heatmap
heatmap = HeatMapWithTime(
data_by_hour,
index=[t.strftime('%H:00') for t in times],
name='Hourly Activity',
auto_play=True,
display_index=True,
max_opacity=0.8,
radius=15,
blur=10
)
heatmap.add_to(m)
m.save('animated_heatmap.html')import folium
from folium.plugins import Draw
m = folium.Map(location=[45.52, -122.67], zoom_start=12)
# Add drawing tools
draw = Draw(
export=True,
filename='my_drawings.geojson',
position='topleft',
draw_options={
'polyline': {'allowIntersection': False},
'polygon': {'allowIntersection': False, 'showArea': True},
'circle': True,
'rectangle': True,
'marker': True,
'circlemarker': False,
},
edit_options={'poly': {'allowIntersection': False}}
)
draw.add_to(m)
# Add some reference data
folium.GeoJson(
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-122.67, 45.52]
},
"properties": {
"name": "Reference Point"
}
},
popup=folium.GeoJsonPopup(fields=['name'])
).add_to(m)
m.save('drawing_map.html')import folium
from folium.plugins import (
GroupedLayerControl,
MiniMap,
MousePosition,
MeasureControl,
Fullscreen
)
m = folium.Map(location=[45.52, -122.67], zoom_start=11)
# Create base layers
osm = folium.TileLayer('OpenStreetMap', name='OpenStreetMap')
cartodb = folium.TileLayer('CartoDB Positron', name='CartoDB Positron')
# Create overlay layers
markers_group = folium.FeatureGroup(name='Markers')
circles_group = folium.FeatureGroup(name='Circles')
# Add some sample data
locations = [[45.51, -122.68], [45.53, -122.66], [45.50, -122.69]]
for i, loc in enumerate(locations):
folium.Marker(loc, popup=f'Marker {i+1}').add_to(markers_group)
folium.Circle(loc, radius=500, color='red', fill=True).add_to(circles_group)
# Add layers to map
osm.add_to(m)
cartodb.add_to(m)
markers_group.add_to(m)
circles_group.add_to(m)
# Grouped layer control
groups = {
'Base Maps': [osm, cartodb],
'Data Layers': [markers_group, circles_group]
}
GroupedLayerControl(groups=groups, exclusive_groups=['Base Maps']).add_to(m)
# Add minimap
minimap = MiniMap(
tile_layer='CartoDB Positron',
position='bottomleft',
width=150,
height=150,
zoom_level_offset=-4
)
minimap.add_to(m)
# Add mouse position display
MousePosition(
position='bottomright',
separator=' | ',
prefix='Coordinates: ',
num_digits=4
).add_to(m)
# Add measurement tool
MeasureControl(
position='topright',
primary_length_unit='meters',
secondary_length_unit='kilometers',
primary_area_unit='sqmeters',
secondary_area_unit='hectares'
).add_to(m)
# Add fullscreen control
Fullscreen(position='topleft').add_to(m)
m.save('advanced_controls.html')Install with Tessl CLI
npx tessl i tessl/pypi-folium