Make beautiful maps with Leaflet.js & Python
—
Advanced data visualization capabilities for displaying and styling geospatial data including GeoJSON rendering, choropleth maps, TopoJSON support, and integration with Vega/Vega-Lite for embedded analytical charts.
Display and style GeoJSON data with interactive features and data-driven styling.
class GeoJson:
"""
Display GeoJSON data on the map with customizable styling.
Parameters:
- data: dict or str, GeoJSON data or URL to GeoJSON
- style_function: callable, function to style features based on properties
- highlight_function: callable, function for hover styling
- 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)
- smooth_factor: float, path smoothing factor (default 1.0)
- tooltip: Tooltip, tooltip for features
- popup: Popup, popup for features
- marker: callable, function to create custom markers for point features
- zoom_on_click: bool, zoom to feature on click (default True)
- embed: bool, embed data in map HTML (default True)
Returns:
GeoJson instance
"""
def __init__(
self,
data,
style_function=None,
highlight_function=None,
name=None,
overlay=True,
control=True,
show=True,
smooth_factor=1.0,
tooltip=None,
popup=None,
marker=None,
zoom_on_click=True,
embed=True,
**kwargs
): ...
class TopoJson:
"""
Display TopoJSON topological data with efficient rendering.
Parameters:
- data: dict or str, TopoJSON data or URL
- object_path: str, path to geometry object in TopoJSON
- style_function: callable, function to style features
- 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)
- smooth_factor: float, path smoothing factor (default 1.0)
- tooltip: Tooltip, tooltip for features
- popup: Popup, popup for features
Returns:
TopoJSON instance
"""
def __init__(
self,
data,
object_path,
style_function=None,
name=None,
overlay=True,
control=True,
show=True,
smooth_factor=1.0,
tooltip=None,
popup=None,
**kwargs
): ...Create thematic maps with data-driven coloring for statistical visualization.
class Choropleth:
"""
Create a choropleth (thematic) map with data-driven coloring.
Parameters:
- geo_data: dict or str, GeoJSON data or URL
- data: DataFrame, data for choropleth coloring
- columns: list, column names [key_column, value_column]
- key_on: str, property path in GeoJSON to match with data
- bins: int or list, number of bins or bin edges for color scale
- fill_color: str, color scale name or list of colors
- nan_fill_color: str, color for missing data (default 'black')
- fill_opacity: float, fill opacity (default 0.7)
- nan_fill_opacity: float, opacity for missing data (default 0.4)
- line_color: str, border color (default 'black')
- line_weight: float, border width (default 1)
- line_opacity: float, border opacity (default 1)
- name: str, layer name for layer control
- legend_name: str, legend title
- overlay: bool, treat as overlay layer (default True)
- control: bool, show in layer control (default True)
- show: bool, show layer initially (default True)
- topojson: str, path to object in TopoJSON (if using TopoJSON)
- smooth_factor: float, path smoothing factor (default 1.0)
- highlight: bool, enable hover highlighting (default False)
- reset: bool, reset style on mouse out (default False)
- popup_keep_highlighted: bool, keep highlighting during popup (default False)
- use_jenks: bool, use Jenks natural breaks (default False)
Returns:
Choropleth instance
"""
def __init__(
self,
geo_data,
data=None,
columns=None,
key_on=None,
bins=6,
fill_color='blue',
nan_fill_color='black',
fill_opacity=0.7,
nan_fill_opacity=0.4,
line_color='black',
line_weight=1,
line_opacity=1,
name=None,
legend_name='',
overlay=True,
control=True,
show=True,
topojson=None,
smooth_factor=1.0,
highlight=False,
reset=False,
popup_keep_highlighted=False,
use_jenks=False,
**kwargs
): ...Specialized popup and tooltip components for displaying feature properties from GeoJSON data.
class GeoJsonPopup:
"""
Create popups specifically for GeoJSON features showing properties.
Parameters:
- fields: list, property names to display
- aliases: list, display names for fields (same order as fields)
- labels: bool, show field labels (default True)
- style: str, CSS styles for popup
- localize: bool, localize numbers and dates (default False)
- sticky: bool, keep popup open on mouse out (default True)
- max_width: int, maximum popup width (default 300)
Returns:
GeoJsonPopup instance
"""
def __init__(
self,
fields=None,
aliases=None,
labels=True,
style=None,
localize=False,
sticky=True,
max_width=300,
**kwargs
): ...
class GeoJsonTooltip:
"""
Create tooltips for GeoJSON features displaying properties.
Parameters:
- fields: list, property names to display
- aliases: list, display names for fields (same order as fields)
- labels: bool, show field labels (default True)
- style: str, CSS styles for tooltip
- localize: bool, localize numbers and dates (default False)
- sticky: bool, follow mouse cursor (default True)
- opacity: float, tooltip opacity (default 0.9)
Returns:
GeoJsonTooltip instance
"""
def __init__(
self,
fields=None,
aliases=None,
labels=True,
style=None,
localize=False,
sticky=True,
opacity=0.9,
**kwargs
): ...
class LatLngPopup:
"""
Display latitude/longitude coordinates in a popup when clicking on the map.
Parameters:
- None (automatically shows coordinates of clicked location)
Returns:
LatLngPopup instance
"""
def __init__(self): ...Embed analytical visualizations using Vega and Vega-Lite grammar within map popups or overlays.
class Vega:
"""
Embed Vega visualizations in map popups or overlays.
Parameters:
- json: dict, Vega specification as dictionary
- width: int, visualization width
- height: int, visualization height
- left: str, left position (default '0%')
- top: str, top position (default '0%')
- position: str, CSS positioning (default 'relative')
Returns:
Vega instance
"""
def __init__(
self,
json,
width=None,
height=None,
left='0%',
top='0%',
position='relative'
): ...
class VegaLite:
"""
Embed Vega-Lite visualizations in map popups or overlays.
Parameters:
- json: dict, Vega-Lite specification as dictionary
- width: int, visualization width
- height: int, visualization height
- left: str, left position (default '0%')
- top: str, top position (default '0%')
- position: str, CSS positioning (default 'relative')
Returns:
VegaLite instance
"""
def __init__(
self,
json,
width=None,
height=None,
left='0%',
top='0%',
position='relative'
): ...Enhanced marker types for data visualization and directional display.
class RegularPolygonMarker:
"""
Create geometric shape markers (triangles, squares, stars, etc.).
Parameters:
- location: tuple, marker coordinates [lat, lon]
- popup: str or Popup, popup content
- tooltip: str or Tooltip, tooltip content
- radius: int, marker radius in pixels (default 15)
- number_of_sides: int, number of polygon sides (default 4 for square)
- rotation: int, rotation angle in degrees (default 0)
- fill_color: str, fill color (default 'blue')
- fill_opacity: float, fill opacity (default 0.6)
- color: str, border color (default 'black')
- weight: int, border width (default 2)
- opacity: float, border opacity (default 1.0)
Returns:
RegularPolygonMarker instance
"""
def __init__(
self,
location,
popup=None,
tooltip=None,
radius=15,
number_of_sides=4,
rotation=0,
fill_color='blue',
fill_opacity=0.6,
color='black',
weight=2,
opacity=1.0,
**kwargs
): ...Advanced styling capabilities for data-driven visualization.
class ColorLine:
"""
Create lines with color gradients based on data values.
Parameters:
- positions: list, line coordinates with optional data values
- colors: list, colors corresponding to positions
- nb_steps: int, number of interpolation steps (default 100)
- weight: int, line width (default 5)
- opacity: float, line opacity (default 1.0)
- popup: str or Popup, popup content
- tooltip: str or Tooltip, tooltip content
Returns:
ColorLine instance
"""
def __init__(
self,
positions,
colors=None,
nb_steps=100,
weight=5,
opacity=1.0,
popup=None,
tooltip=None,
**kwargs
): ...import folium
import json
# Load GeoJSON data
with open('counties.geojson', 'r') as f:
counties_data = json.load(f)
# Create map
m = folium.Map(location=[39.8283, -98.5795], zoom_start=5)
# Style function based on properties
def style_function(feature):
return {
'fillColor': '#ffff00',
'color': 'black',
'weight': 2,
'fillOpacity': 0.7,
}
# Highlight function for hover effect
def highlight_function(feature):
return {
'fillColor': '#ff0000',
'color': 'black',
'weight': 3,
'fillOpacity': 0.9,
}
# Add GeoJSON with styling
folium.GeoJson(
counties_data,
style_function=style_function,
highlight_function=highlight_function,
popup=folium.GeoJsonPopup(fields=['NAME', 'POPULATION']),
tooltip=folium.GeoJsonTooltip(fields=['NAME'])
).add_to(m)
m.save('styled_geojson.html')import folium
import pandas as pd
import json
# Load data
df = pd.read_csv('unemployment_data.csv')
with open('us_states.geojson', 'r') as f:
state_geo = json.load(f)
# Create map
m = folium.Map(location=[48, -102], zoom_start=3)
# Create choropleth
folium.Choropleth(
geo_data=state_geo,
name='Unemployment Rate',
data=df,
columns=['State', 'Unemployment'],
key_on='feature.properties.NAME',
fill_color='YlOrRd',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Unemployment Rate (%)',
bins=5,
highlight=True
).add_to(m)
folium.LayerControl().add_to(m)
m.save('choropleth.html')import folium
# Vega-Lite chart specification
chart_spec = {
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"data": {"values": [
{"a": "A", "b": 28}, {"a": "B", "b": 55},
{"a": "C", "b": 43}, {"a": "D", "b": 91}
]},
"mark": "bar",
"encoding": {
"x": {"field": "a", "type": "nominal"},
"y": {"field": "b", "type": "quantitative"}
}
}
# Create map
m = folium.Map(location=[45.52, -122.67], zoom_start=11)
# Create Vega-Lite visualization
chart = folium.VegaLite(chart_spec, width=300, height=200)
# Add marker with chart in popup
folium.Marker(
[45.52, -122.67],
popup=folium.Popup().add_child(chart)
).add_to(m)
m.save('vega_popup.html')import folium
import numpy as np
# Generate path data with values
path_coords = [[45.5, -122.7], [45.51, -122.69], [45.52, -122.68]]
path_values = [10, 25, 40] # Data values for coloring
# Create color gradient from values
colors = ['blue', 'yellow', 'red']
m = folium.Map(location=[45.51, -122.69], zoom_start=13)
# Add color line
folium.ColorLine(
positions=list(zip(path_coords, path_values)),
colors=colors,
weight=8,
opacity=0.8,
tooltip='Dynamic colored path'
).add_to(m)
m.save('color_line.html')Install with Tessl CLI
npx tessl i tessl/pypi-folium