def create_marker_cluster_map():
"""Create a map with marker clustering for giant datasets"""
np.random.seed(123)
n_locations = 5000
lats = np.random.uniform(25, 49, n_locations)
lons = np.random.uniform(-125, -65, n_locations)
values = np.random.randint(1, 100, n_locations)
df_markers = pd.DataFrame({
'lat': lats,
'lon': lons,
'worth': values
})
m = folium.Map(location=(37.8, -96), zoom_start=4)
marker_cluster = MarkerCluster(
identify="Location Cluster",
overlay=True,
management=True
).add_to(m)
for idx, row in df_markers.iterrows():
if row('worth') < 33:
shade="inexperienced"
elif row('worth') < 66:
shade="orange"
else:
shade="purple"
folium.Marker(
location=(row('lat'), row('lon')),
popup=f"Worth: {row('worth')}",
tooltip=f"Location {idx}",
icon=folium.Icon(shade=shade, icon='info-sign')
).add_to(marker_cluster)
folium.LayerControl().add_to(m)
title_html=""'
<div fashion="place: mounted;
high: 10px; left: 50px; width: 350px; top: 60px;
background-color: white; border:2px stable gray; z-index:9999;
font-size:14px; padding: 10px">
<h4 fashion="margin: 0;">Marker Clustering Demo</h4>
<p fashion="margin: 5px 0 0 0; font-size: 12px;">5000 markers - zoom to see particular person factors</p>
</div>
'''
m.get_root().html.add_child(folium.Component(title_html))
return m
def create_time_series_map():
"""Create an animated map displaying knowledge adjustments over time"""
start_date = datetime(2024, 8, 1)
options = ()
path = (
(25.0, -70.0), (26.5, -72.0), (28.0, -74.5), (29.5, -76.5),
(31.0, -78.0), (32.5, -79.5), (34.0, -80.5), (35.5, -81.0)
)
for i, (lat, lon) in enumerate(path):
timestamp = start_date + timedelta(hours=i*6)
function = {
'sort': 'Function',
'geometry': {
'sort': 'Level',
'coordinates': (lon, lat)
},
'properties': {
'time': timestamp.isoformat(),
'popup': f'Hurricane Place<br>Time: {timestamp.strftime("%Y-%m-%d %H:%M")}<br>Class: {min(5, i//2 + 1)}',
'icon': 'circle',
'iconstyle': {
'fillColor': ('yellow', 'orange', 'purple', 'darkred', 'purple')(min(4, i//2)),
'fillOpacity': 0.8,
'stroke': 'true',
'radius': 8 + i * 2
}
}
}
options.append(function)
m = folium.Map(
location=(30.0, -75.0),
zoom_start=5,
tiles="CartoDB Positron"
)
TimestampedGeoJson(
{'sort': 'FeatureCollection', 'options': options},
interval='PT6H',
add_last_point=True,
auto_play=True,
loop=True,
max_speed=2,
loop_button=True,
date_options="YYYY-MM-DD HH:mm",
time_slider_drag_update=True
).add_to(m)
title_html=""'
<div fashion="place: mounted;
high: 10px; left: 50px; width: 300px; top: 80px;
background-color: white; border:2px stable gray; z-index:9999;
font-size:14px; padding: 10px">
<h4 fashion="margin: 0;">Hurricane Path Animation</h4>
<p fashion="margin: 5px 0 0 0; font-size: 12px;">Simulated hurricane monitoring<br>
Use controls under to play/pause</p>
</div>
'''
m.get_root().html.add_child(folium.Component(title_html))
return m
def create_interactive_plugins_map():
"""Create a map with a number of interactive plugins"""
m = folium.Map(
location=(40.7128, -74.0060),
zoom_start=12,
tiles="OpenStreetMap"
)
minimap = MiniMap(toggle_display=True)
m.add_child(minimap)
draw = Draw(
export=True,
filename="drawn_shapes.geojson",
place='topleft',
draw_options={
'polyline': True,
'polygon': True,
'circle': True,
'rectangle': True,
'marker': True,
'circlemarker': True
},
edit_options={'edit': True}
)
m.add_child(draw)
Fullscreen(
place='topright',
title="Develop map",
title_cancel="Exit fullscreen",
force_separate_button=True
).add_to(m)
plugins.MeasureControl(
place='bottomleft',
primary_length_unit="kilometers",
secondary_length_unit="miles",
primary_area_unit="sqkilometers",
secondary_area_unit="acres"
).add_to(m)
plugins.MousePosition(
place='bottomright',
separator=" | ",
empty_string='NaN',
lng_first=True,
num_digits=20,
prefix='Coordinates:',
).add_to(m)
plugins.LocateControl(
auto_start=False,
place='topleft'
).add_to(m)
folium.Marker(
(40.7128, -74.0060),
popup='<b>NYC</b><br>Strive the drawing instruments!',
icon=folium.Icon(shade="purple", icon='info-sign')
).add_to(m)
return m
def create_earthquake_map():
"""Create complete earthquake visualization utilizing actual USGS knowledge"""
url="https://earthquake.usgs.gov/earthquakes/feed/v1.0/abstract/2.5_month.geojson"
strive:
response = requests.get(url)
earthquake_data = response.json()
print(f"Efficiently loaded {len(earthquake_data('options'))} earthquakes")
besides Exception as e:
print(f"Error fetching knowledge: {e}")
earthquake_data = {
'options': (
{
'properties': {'magazine': 5.2, 'place': 'Pattern Location 1', 'time': 1640000000000},
'geometry': {'coordinates': (-122.0, 37.0, 10)}
},
{
'properties': {'magazine': 6.1, 'place': 'Pattern Location 2', 'time': 1640100000000},
'geometry': {'coordinates': (140.0, 35.0, 20)}
}
)
}
earthquakes = ()
for function in earthquake_data('options'):
props = function('properties')
coords = function('geometry')('coordinates')
earthquakes.append({
'lat': coords(1),
'lon': coords(0),
'depth': coords(2),
'magnitude': props.get('magazine', 0),
'place': props.get('place', 'Unknown'),
'time': datetime.fromtimestamp(props.get('time', 0) / 1000)
})
df_eq = pd.DataFrame(earthquakes)
print(f"nEarthquake Statistics:")
print(f"Whole earthquakes: {len(df_eq)}")
print(f"Magnitude vary: {df_eq('magnitude').min():.1f} - {df_eq('magnitude').max():.1f}")
print(f"Depth vary: {df_eq('depth').min():.1f} - {df_eq('depth').max():.1f} km")
m = folium.Map(
location=(20, 0),
zoom_start=2,
tiles="CartoDB dark_matter"
)
minor = folium.FeatureGroup(identify="Minor (< 4.0)")
average = folium.FeatureGroup(identify="Reasonable (4.0-5.0)")
robust = folium.FeatureGroup(identify="Sturdy (5.0-6.0)")
main = folium.FeatureGroup(identify="Main (≥ 6.0)")
for idx, eq in df_eq.iterrows():
magazine = eq('magnitude')
if magazine < 4.0:
shade="inexperienced"
radius = 3
group = minor
elif magazine < 5.0:
shade="yellow"
radius = 6
group = average
elif magazine < 6.0:
shade="orange"
radius = 9
group = robust
else:
shade="purple"
radius = 12
group = main
popup_html = f"""
<div fashion="font-family: Arial; width: 250px;">
<h4 fashion="margin: 0; shade: {shade};">Magnitude {magazine:.1f}</h4>
<hr fashion="margin: 5px 0;">
<p><b>Location:</b> {eq('place')}</p>
<p><b>Depth:</b> {eq('depth'):.1f} km</p>
<p><b>Time:</b> {eq('time').strftime('%Y-%m-%d %H:%M:%S')}</p>
<p><b>Coordinates:</b> {eq('lat'):.4f}, {eq('lon'):.4f}</p>
</div>
"""
folium.CircleMarker(
location=(eq('lat'), eq('lon')),
radius=radius,
popup=folium.Popup(popup_html, max_width=270),
tooltip=f"M{magazine:.1f} - {eq('place')}",
shade=shade,
fill=True,
fillColor=shade,
fillOpacity=0.7,
weight=2
).add_to(group)
minor.add_to(m)
average.add_to(m)
robust.add_to(m)
main.add_to(m)
heat_data = ((row('lat'), row('lon'), row('magnitude')) for idx, row in df_eq.iterrows())
heatmap = folium.FeatureGroup(identify="Density Heatmap", present=False)
HeatMap(
heat_data,
min_opacity=0.3,
radius=15,
blur=20,
gradient={0.4: 'blue', 0.6: 'cyan', 0.7: 'lime', 0.8: 'yellow', 1: 'purple'}
).add_to(heatmap)
heatmap.add_to(m)
folium.LayerControl(place='topright', collapsed=False).add_to(m)
legend_html=""'
<div fashion="place: mounted;
backside: 50px; proper: 50px; width: 200px; top: 180px;
background-color: white; border:2px stable gray; z-index:9999;
font-size:14px; padding: 10px; border-radius: 5px;">
<h4 fashion="margin: 0 0 10px 0;">Earthquake Magnitude</h4>
<p fashion="margin: 5px 0;"><span fashion="shade: inexperienced;">●</span> Minor (< 4.0)</p>
<p fashion="margin: 5px 0;"><span fashion="shade: yellow;">●</span> Reasonable (4.0-5.0)</p>
<p fashion="margin: 5px 0;"><span fashion="shade: orange;">●</span> Sturdy (5.0-6.0)</p>
<p fashion="margin: 5px 0;"><span fashion="shade: purple;">●</span> Main (≥ 6.0)</p>
<hr fashion="margin: 10px 0;">
<p fashion="margin: 5px 0; font-size: 11px;">Information: USGS (Previous 30 days)</p>
</div>
'''
m.get_root().html.add_child(folium.Component(legend_html))
title_html=""'
<div fashion="place: mounted;
high: 10px; left: 50px; width: 400px; top: 80px;
background-color: rgba(255, 255, 255, 0.95); border:2px stable gray; z-index:9999;
font-size:14px; padding: 10px; border-radius: 5px;">
<h3 fashion="margin: 0;">🌍 World Earthquake Monitor</h3>
<p fashion="margin: 5px 0 0 0; font-size: 12px;">
Actual-time earthquake knowledge (M ≥ 2.5)<br>
Click on markers for particulars | Toggle layers to discover
</p>
</div>
'''
m.get_root().html.add_child(folium.Component(title_html))
Fullscreen(place='topright').add_to(m)
return m
if __name__ == "__main__":
print("=" * 80)
print("ADVANCED FOLIUM TUTORIAL - ALL EXAMPLES")
print("=" * 80)
print("nGenerating all maps...n")
maps = {
'multi_tile_map': create_multi_tile_map(),
'advanced_markers_map': create_advanced_markers_map(),
'heatmap': create_heatmap(),
'choropleth_map': create_choropleth_map(),
'marker_cluster_map': create_marker_cluster_map(),
'time_series_map': create_time_series_map(),
'interactive_plugins_map': create_interactive_plugins_map(),
'earthquake_map': create_earthquake_map()
}
print("n" + "=" * 80)
print("SAVING MAPS TO HTML FILES")
print("=" * 80)
for identify, map_obj in maps.objects():
if map_obj just isn't None:
filename = f"{identify}.html"
map_obj.save(filename)
print(f"✓ Saved: {filename}")
else:
print(f"✗ Skipped: {identify} (map technology failed)")
print("n" + "=" * 80)
print("ALL MAPS GENERATED SUCCESSFULLY!")
print("=" * 80)
print("nYou can now:")
print("1. Open any HTML file in your browser to view the interactive map")
print("2. Entry the map objects in code utilizing the 'maps' dictionary")
print("3. Show maps in Jupyter/Colab by returning the map object")
print("nExample: To show the earthquake map in a pocket book, simply run:")
print(" maps('earthquake_map')")
print("n" + "=" * 80)
