### Initialize WebGLEarth Globe
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Basic setup for creating a WebGLEarth globe instance with specified center and zoom level.
```python
>>> import folium
>>> from folium.plugins import WebGLEarth, WebGLEarthMarker
>>> m = folium.Map()
>>> globe = WebGLEarth(center=[48.2, 16.4], zoom=4)
>>> globe.add_to(m)
```
--------------------------------
### Flask App with Fullscreen Folium Map
Source: https://github.com/python-visualization/folium/blob/main/docs/advanced_guide/flask.md
This example shows the simplest way to display a Folium map in a Flask app by rendering its HTML representation directly. Ensure Flask and Folium are installed.
```python
"""flask_example.py
Required packages:
- flask
- folium
Usage:
Start the flask server by running:
$ python flask_example.py
And then head to http://127.0.0.1:5000/ in your browser to see the map displayed
"""
from flask import Flask, render_template_string
import folium
app = Flask(__name__)
@app.route("/")
def fullscreen():
"""Simple example of a fullscreen map."""
m = folium.Map()
return m.get_root().render()
@app.route("/iframe")
def iframe():
"""Embed a map as an iframe on a page."""
m = folium.Map()
# set the iframe width and height
m.get_root().width = "800px"
m.get_root().height = "600px"
iframe = m.get_root()._repr_html_()
return render_template_string(
"""
Using an iframe
{{ iframe|safe }}
""",
iframe=iframe,
)
@app.route("/components")
def components():
"""Extract map components and put those on a page."""
m = folium.Map(
width=800,
height=600,
)
m.get_root().render()
header = m.get_root().header.render()
body_html = m.get_root().html.render()
script = m.get_root().script.render()
return render_template_string(
"""
{{ header|safe }}
Using components
{{ body_html|safe }}
""",
header=header,
body_html=body_html,
script=script,
)
if __name__ == "__main__":
app.run(debug=True)
```
--------------------------------
### Install Folium using pip
Source: https://github.com/python-visualization/folium/blob/main/docs/getting_started.md
Use pip to install the Folium library. This is the standard method for Python package installation.
```bash
$ pip install folium
```
--------------------------------
### Install Folium using pip
Source: https://github.com/python-visualization/folium/blob/main/README.rst
Use this command to install the folium library via pip. Ensure you have pip installed.
```bash
pip install folium
```
--------------------------------
### Initialize WebGLEarth Map
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/webgl_earth.md
Basic setup for creating a Folium map with the WebGLEarth plugin. This initializes the globe and adds markers.
```python
import folium
from folium.plugins import WebGLEarth, WebGLEarthMarker
m = folium.Map()
globe = WebGLEarth(center=[20, 0], zoom=2)
globe.add_to(m)
WebGLEarthMarker(location=[48.8566, 2.3522], popup="Paris").add_to(globe)
WebGLEarthMarker(location=[35.6762, 139.6503], popup="Tokyo").add_to(globe)
WebGLEarthMarker(location=[40.7128, -74.0060], popup="New York").add_to(globe)
m
```
--------------------------------
### Simple Realtime Example with Static GeoJSON
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/realtime.md
Demonstrates using a static GeoJSON file as a data source for the Realtime plugin. Normally, a URL that updates in real-time would be used.
```python
from folium import JsCode
m = folium.Map(location=[40.73, -73.94], zoom_start=12)
rt = folium.plugins.Realtime(
"https://raw.githubusercontent.com/python-visualization/folium-example-data/main/subway_stations.geojson",
get_feature_id=JsCode("(f) => { return f.properties.objectid; }"),
interval=10000,
)
rt.add_to(m)
m
```
--------------------------------
### Basic AntPath Example
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/antpath.md
Demonstrates how to create and add an AntPath to a Folium map. Customize the path's appearance using `reverse` and `dash_array` options.
```python
import folium
import folium.plugins
m = folium.Map()
wind_locations = [
[59.35560, -31.992190],
[55.178870, -42.89062],
[47.754100, -43.94531],
[38.272690, -37.96875],
[27.059130, -41.13281],
[16.299050, -36.56250],
[8.4071700, -30.23437],
[1.0546300, -22.50000],
[-8.754790, -18.28125],
[-21.61658, -20.03906],
[-31.35364, -24.25781],
[-39.90974, -30.93750],
[-43.83453, -41.13281],
[-47.75410, -49.92187],
[-50.95843, -54.14062],
[-55.97380, -56.60156],
]
folium.plugins.AntPath(
locations=wind_locations, reverse="True", dash_array=[20, 30]
).add_to(m)
m.fit_bounds(m.get_bounds())
m
```
--------------------------------
### Configure MousePosition Plugin
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Example of configuring the MousePosition plugin with custom formatters for latitude and longitude.
```python
>>> fmtr = "function(num) {return L.Util.formatNum(num, 3) + ' º ';}"
>>> MousePosition(
... position="topright",
... separator=" | ",
... prefix="Mouse:",
... lat_formatter=fmtr,
... lng_formatter=fmtr,
... )
```
--------------------------------
### Install Folium using Conda
Source: https://github.com/python-visualization/folium/blob/main/README.rst
Use this command to install the folium library via Conda. This is an alternative installation method.
```bash
conda install -c conda-forge folium
```
--------------------------------
### Basic FitOverlays Example
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/features/fit_overlays.md
Demonstrates how to use FitOverlays to automatically adjust the map view to fit enabled feature groups. Initially, only the first marker is visible; enabling the second marker triggers a view change.
```python
m = folium.Map((52, 0), tiles='cartodbpositron', zoom_start=8)
fg1 = folium.FeatureGroup().add_to(m)
folium.Marker((52, 5)).add_to(fg1)
fg2 = folium.FeatureGroup(show=False).add_to(m)
folium.Marker((52, 5.1)).add_to(fg2)
folium.FitOverlays().add_to(m)
folium.LayerControl().add_to(m)
m
```
--------------------------------
### Create Folium Map with Different Options
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Demonstrates creating a Folium map with default settings, custom tiles, and custom tile URLs with attribution. Ensure you have the folium library installed.
```python
>>> m = folium.Map(location=[45.523, -122.675], width=750, height=500)
```
```python
>>> m = folium.Map(location=[45.523, -122.675], tiles="cartodb positron")
```
```python
>>> m = folium.Map(
... location=[45.523, -122.675],
... zoom_start=2,
... tiles="https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=mytoken",
... attr="Mapbox attribution",
... )
```
--------------------------------
### Create a Basic Folium Map
Source: https://github.com/python-visualization/folium/blob/main/docs/getting_started.md
Initialize a Folium map centered at a specific location. This is the starting point for most Folium visualizations.
```python
import folium
m = folium.Map(location=(45.5236, -122.6750))
```
```python
m
```
```python
m.save("index.html")
```
--------------------------------
### Import Folium and Load Data
Source: https://github.com/python-visualization/folium/blob/main/docs/advanced_guide/custom_tiles.md
Imports the folium library and loads US states data for use in examples. This is a prerequisite for most subsequent examples.
```python
import folium
```
```python
import requests
states = requests.get(
"https://raw.githubusercontent.com/python-visualization/folium-example-data/main/us_states.json"
).json()
kw = {"location": [48, -102], "zoom_start": 3}
```
--------------------------------
### Example: Initialize Map for Envelope Polygon
Source: https://github.com/python-visualization/folium/blob/main/docs/advanced_guide/polygons_from_list_of_points.md
Initializes a Folium map centered on a specific location with a given zoom level, ready for adding an envelope polygon.
```python
# Initialize map
my_envelope_map = folium.Map(location=[49.5, 8.5], zoom_start=8)
```
--------------------------------
### Live ISS Tracker with WebGLEarthRealtime
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/webgl_earth.md
Implement a live tracker for the International Space Station using WebGLEarthRealtime. This example fetches data from a public API and updates a marker on the globe.
```python
import folium
from folium import JsCode
from folium.plugins import WebGLEarth, WebGLEarthRealtime
m = folium.Map()
globe = WebGLEarth(center=[0, 0], zoom=1.8)
globe.add_to(m)
WebGLEarthRealtime(
source_url="https://api.wheretheiss.at/v1/satellites/25544",
interval=3000,
on_update=JsCode("""
function(data, earth) {
if (window._issMarker) window._issMarker.removeFrom(earth);
window._issMarker = WE.marker(
[data.latitude, data.longitude]
).addTo(earth);
window._issMarker.bindPopup(
'ISS
'
+ 'Lat: ' + data.latitude.toFixed(2)
+ '
Lng: ' + data.longitude.toFixed(2)
+ '
Alt: ' + data.altitude.toFixed(1) + ' km'
);
}
""",
).add_to(globe)
m
```
--------------------------------
### Import Libraries for Folium Visualization
Source: https://github.com/python-visualization/folium/blob/main/docs/advanced_guide/choropleth with Jenks natural breaks optimization.md
Imports necessary libraries for data manipulation and visualization with Folium. Ensure these are installed before running.
```python
import folium
import numpy as np
import pandas as pd
import json
import requests
```
--------------------------------
### Simple TreeLayerControl Example
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/treelayercontrol.md
Demonstrates how to create a Folium map and add a TreeLayerControl with nested layers and markers. The overlay_tree dictionary defines the structure and content of the layer control.
```python
import folium
from folium.plugins.treelayercontrol import TreeLayerControl
from folium.features import Marker
m = folium.Map(location=[46.603354, 1.8883335], zoom_start=5)
overlay_tree = {
"label": "Points of Interest",
"select_all_checkbox": "Un/select all",
"children": [
{
"label": "Europe",
"select_all_checkbox": True,
"children": [
{
"label": "France",
"select_all_checkbox": True,
"children": [
{ "label": "Tour Eiffel", "layer": Marker([48.8582441, 2.2944775]).add_to(m) },
{ "label": "Notre Dame", "layer": Marker([48.8529540, 2.3498726]).add_to(m) },
{ "label": "Louvre", "layer": Marker([48.8605847, 2.3376267]).add_to(m) },
]
}, {
"label": "Germany",
"select_all_checkbox": True,
"children": [
{ "label": "Branderburger Tor", "layer": Marker([52.5162542, 13.3776805]).add_to(m)},
{ "label": "Kölner Dom", "layer": Marker([50.9413240, 6.9581201]).add_to(m)},
]
}, {"label": "Spain",
"select_all_checkbox": "De/seleccionar todo",
"children": [
{ "label": "Palacio Real", "layer": Marker([40.4184145, -3.7137051]).add_to(m)},
{ "label": "La Alhambra", "layer": Marker([37.1767829, -3.5892795]).add_to(m)},
]
}
]
}, {
"label": "Asia",
"select_all_checkbox": True,
"children": [
{
"label": "Jordan",
"select_all_checkbox": True,
"children": [
{ "label": "Petra", "layer": Marker([30.3292215, 35.4432464]).add_to(m) },
{ "label": "Wadi Rum", "layer": Marker([29.6233486, 35.4390656]).add_to(m) }
]
}, {
}
]
}
]
}
TreeLayerControl(overlay_tree=overlay_tree).add_to(m)
m
```
--------------------------------
### Flask App with Extracted Folium Map Components
Source: https://github.com/python-visualization/folium/blob/main/docs/advanced_guide/flask.md
This example demonstrates how to extract individual components (header, HTML body, script) of a Folium map and manually integrate them into a Flask template. This offers fine-grained control over map placement. Requires Flask and Folium.
```python
m = folium.Map(
width=800,
height=600,
)
m.get_root().render()
header = m.get_root().header.render()
body_html = m.get_root().html.render()
script = m.get_root().script.render()
return render_template_string(
"""
{{ header|safe }}
Using components
{{ body_html|safe }}
""",
header=header,
body_html=body_html,
script=script,
)
```
--------------------------------
### Create Basic Choropleth Map
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/geojson/choropleth.md
Creates a basic Choropleth map using GeoJSON data for US states. This example initializes a map and adds a Choropleth layer with specified fill and line opacity.
```python
import folium
import requests
m = folium.Map([43, -100], zoom_start=4)
us_states = requests.get(
"https://raw.githubusercontent.com/python-visualization/folium-example-data/main/us_states.json"
).json()
folium.Choropleth(
geo_data=us_states,
fill_opacity=0.3,
line_weight=2,
).add_to(m)
m
```
--------------------------------
### Basic PolyLineTextPath Usage
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/polyline_textpath.md
This snippet shows how to create a map and add a PolyLine with text labels along its path using PolyLineTextPath. It includes examples with different text, colors, and offsets.
```python
import folium
import folium.plugins
m = folium.Map([30, 0], zoom_start=3)
wind_locations = [
[59.35560, -31.992190],
[55.178870, -42.89062],
[47.754100, -43.94531],
[38.272690, -37.96875],
[27.059130, -41.13281],
[16.299050, -36.56250],
[8.4071700, -30.23437],
[1.0546300, -22.50000],
[-8.754790, -18.28125],
[-21.61658, -20.03906],
[-31.35364, -24.25781],
[-39.90974, -30.93750],
[-43.83453, -41.13281],
[-47.75410, -49.92187],
[-50.95843, -54.14062],
[-55.97380, -56.60156],
]
wind_line = folium.PolyLine(wind_locations, weight=15, color="#8EE9FF").add_to(m)
attr = {"fill": "#007DEF", "font-weight": "bold", "font-size": "24"}
folium.plugins.PolyLineTextPath(
wind_line, ") ", repeat=True, offset=7, attributes=attr
).add_to(m)
danger_line = folium.PolyLine(
[[-40.311, -31.952], [-12.086, -18.727]], weight=10, color="orange", opacity=0.8
).add_to(m)
attr = {"fill": "red"}
folium.plugins.PolyLineTextPath(
danger_line, "\u25BA", repeat=True, offset=6, attributes=attr
).add_to(m)
plane_line = folium.PolyLine(
[[-49.38237, -37.26562], [-1.75754, -14.41406], [51.61802, -23.20312]],
weight=1,
color="black",
).add_to(m)
attr = {"font-weight": "bold", "font-size": "24"}
folium.plugins.PolyLineTextPath(
plane_line, "\u2708 ", repeat=True, offset=8, attributes=attr
).add_to(m)
line_to_new_delhi = folium.PolyLine(
[
[46.67959447, 3.33984375],
[46.5588603, 29.53125],
[42.29356419, 51.328125],
[35.74651226, 68.5546875],
[28.65203063, 76.81640625],
]
).add_to(m)
line_to_hanoi = folium.PolyLine(
[
[28.76765911, 77.60742188],
[27.83907609, 88.72558594],
[25.68113734, 97.3828125],
[21.24842224, 105.77636719],
]
).add_to(m)
folium.plugins.PolyLineTextPath(line_to_new_delhi, "To New Delhi", offset=-5).add_to(m)
folium.plugins.PolyLineTextPath(line_to_hanoi, "To Hanoi", offset=-5).add_to(m)
m
```
--------------------------------
### Create Timestamped GeoJSON Layer
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/timestamped_geojson.md
This example shows how to create a TimestampedGeoJson layer with multiple points and a LineString, each with associated time-based properties. It configures playback options like period, auto-play, and loop.
```python
table = """
| Firstname |
Lastname |
Age |
| Jill |
Smith |
50 |
| Eve |
Jackson |
94 |
"""
points = [
{
"time": "2017-06-02",
"popup": "address1
",
"coordinates": [-2.548828, 51.467697],
},
{
"time": "2017-07-02",
"popup": "address2",
"coordinates": [-0.087891, 51.536086],
},
{
"time": "2017-08-02",
"popup": "address3",
"coordinates": [-6.240234, 53.383328],
},
{
"time": "2017-09-02",
"popup": "address4",
"coordinates": [-1.40625, 60.261617],
},
{"time": "2017-10-02", "popup": table, "coordinates": [-1.516113, 53.800651]},
]
features = [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": point["coordinates"],
},
"properties": {
"time": point["time"],
"popup": point["popup"],
"id": "house",
"icon": "marker",
"iconstyle": {
"iconUrl": "https://leafletjs.com/examples/geojson/baseball-marker.png",
"iconSize": [20, 20],
},
},
}
for point in points
]
features.append(
{
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": [
[-2.548828, 51.467697],
[-0.087891, 51.536086],
[-6.240234, 53.383328],
[-1.40625, 60.261617],
[-1.516113, 53.800651],
],
},
"properties": {
"popup": "Current address",
"times": [
"2017-06-02",
"2017-07-02",
"2017-08-02",
"2017-09-02",
"2017-10-02",
],
"icon": "circle",
"iconstyle": {
"fillColor": "green",
"fillOpacity": 0.6,
"stroke": "false",
"radius": 13,
},
"style": {"weight": 0},
"id": "man",
},
}
)
m = folium.Map(
location=[56.096555, -3.64746],
tiles="cartodbpositron",
zoom_start=5,
)
folium.plugins.TimestampedGeoJson(
{"type": "FeatureCollection", "features": features},
period="P1M",
add_last_point=True,
auto_play=False,
loop=False,
max_speed=1,
loop_button=True,
date_options="YYYY/MM/DD",
time_slider_drag_update=True,
duration="P2M",
).add_to(m)
m
```
--------------------------------
### Bus Lines Demo with Automatic Offset Calculation
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/polyline_offset.md
Demonstrates a more complex use case where offsets are computed automatically based on the number of bus lines sharing a segment. This example also utilizes non-offset polylines to create white and black outline effects.
```python
m = folium.Map(location=[48.868, 2.365], zoom_start=15)
geojson = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {"lines": [0, 1]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.357919216156006, 48.87621773324153],
[2.357339859008789, 48.874834693731664],
[2.362983226776123, 48.86855408432749],
[2.362382411956787, 48.86796126699168],
[2.3633265495300293, 48.86735432768131],
],
},
},
{
"type": "Feature",
"properties": {"lines": [2, 3]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.351503372192383, 48.86443950493823],
[2.361609935760498, 48.866775611250205],
[2.3633265495300293, 48.86735432768131],
],
},
},
{
"type": "Feature",
"properties": {"lines": [1, 2]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.369627058506012, 48.86619159489603],
[2.3724031448364253, 48.8626397112042],
[2.3728322982788086, 48.8616233285001],
[2.372767925262451, 48.86080456075567],
],
},
},
{
"type": "Feature",
"properties": {"lines": [0]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.3647427558898926, 48.86653565369396],
[2.3647642135620117, 48.86630981023694],
[2.3666739463806152, 48.86314789481612],
[2.3673176765441895, 48.86066339254944],
],
},
},
{
"type": "Feature",
"properties": {"lines": [0, 1, 2, 3]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.3633265495300293, 48.86735432768131],
[2.3647427558898926, 48.86653565369396],
],
},
},
{
"type": "Feature",
"properties": {"lines": [1, 2, 3]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.3647427558898926, 48.86653565369396],
[2.3650002479553223, 48.86660622956524],
[2.365509867668152, 48.866987337550164],
[2.369627058506012, 48.86619159489603],
],
},
},
{
"type": "Feature",
"properties": {"lines": [3]},
"geometry": {
"type": "LineString",
"coordinates": [
[2.369627058506012, 48.86619159489603],
[2.372349500656128, 48.865702850895744],
],
},
},
],
}
```
--------------------------------
### Create Image Overlay with NumPy
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/raster_layers/image_overlay.md
Generate an image dynamically using NumPy for display on the map. Requires NumPy to be installed. A colormap function is needed to define how the NumPy array values are rendered as colors.
```python
import numpy as np
image = np.zeros((61, 61))
image[0, :] = 1.0
image[60, :] = 1.0
image[:, 0] = 1.0
image[:, 60] = 1.0
```
```python
m = folium.Map([37, 0], zoom_start=2)
folium.raster_layers.ImageOverlay(
image=image,
bounds=[[0, -60], [60, 60]],
colormap=lambda x: (1, 0, 0, x),
).add_to(m)
m
```
--------------------------------
### Create WebGLEarthMarker Instance
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Demonstrates creating a WebGLEarthMarker with location and popup, and adding it to a WebGLEarth globe.
```python
>>> globe = WebGLEarth()
>>> marker = WebGLEarthMarker(
... location=[48.2, 16.4],
... popup="Vienna",
... )
>>> marker.add_to(globe)
```
--------------------------------
### Create and Save a DualMap
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Demonstrates how to initialize a DualMap with custom tiles and zoom level, add markers to both maps, and save the resulting HTML file. The individual maps are accessible via `m1` and `m2` attributes.
```pycon
>>> # DualMap accepts the same arguments as Map:
>>> m = DualMap(location=(0, 0), tiles="cartodbpositron", zoom_start=5)
>>> # Add the same marker to both maps:
>>> Marker((0, 0)).add_to(m)
>>> # The individual maps are attributes called `m1` and `m2`:
>>> Marker((0, 1)).add_to(m.m1)
>>> LayerControl().add_to(m)
>>> m.save("map.html")
```
--------------------------------
### VectorGridProtobuf with Options as Dictionary
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Demonstrates how to configure VectorGridProtobuf using a Python dictionary for options, including vector tile layer styles.
```python
>>> m = folium.Map()
>>> url = "https://free-{s}.tilehosting.com/data/v3/{z}/{x}/{y}.pbf?token={token}"
>>> options = {
... "subdomain": "tilehosting",
... "token": "af6P2G9dztAt1F75x7KYt0Hx2DJR052G",
... "vectorTileLayerStyles": {
... "layer_name_one": {
... "fill": True,
... "weight": 1,
... "fillColor": "green",
... "color": "black",
... "fillOpacity": 0.6,
... "opacity": 0.6,
... },
... "layer_name_two": {
... "fill": True,
... "weight": 1,
... "fillColor": "red",
... "color": "black",
... "fillOpacity": 0.6,
... "opacity": 0.6,
... },
... },
... }
>>> VectorGridProtobuf(url, "layer_name", options).add_to(m)
```
--------------------------------
### Install Folium using Conda
Source: https://github.com/python-visualization/folium/blob/main/docs/getting_started.md
If you are using the Conda package manager, install Folium from the conda-forge channel.
```bash
$ conda install folium -c conda-forge
```
--------------------------------
### Create a Basic DualMap
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/dual_map.md
Instantiate a DualMap with a specified location and zoom level. Panning and zooming on one map will synchronize with the other.
```python
import folium
import folium.plugins
folium.plugins.DualMap(location=(52.1, 5.1), zoom_start=8)
```
--------------------------------
### Get Unique Service Levels
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/geojson/geojson_marker.md
Retrieves a list of unique service levels from the GeoDataFrame.
```python
service_levels = gdf.service_level.unique().tolist()
service_levels
```
--------------------------------
### VectorGridProtobuf with Options as String
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Shows how to configure VectorGridProtobuf using a JavaScript string for options, allowing for dynamic styling functions.
```python
>>> m = folium.Map()
>>> url = "https://free-{s}.tilehosting.com/data/v3/{z}/{x}/{y}.pbf?token={token}"
>>> options = '''{
... "subdomain": "tilehosting",
... "token": "af6P2G9dztAt1F75x7KYt0Hx2DJR052G",
... "vectorTileLayerStyles": {
... all: function(f) {
... if (f.type === 'parks') {
... return {
... "fill": true,
... "weight": 1,
... "fillColor": 'green',
... "color": 'black',
... "fillOpacity":0.6,
... "opacity":0.6
... };
... }
... if (f.type === 'water') {
... return {
... "fill": true,
... "weight": 1,
... "fillColor": 'purple',
... "color": 'black',
... "fillOpacity":0.6,
... "opacity":0.6
... };
... }
... }
... }
... }'''
>>> VectorGridProtobuf(url, "layer_name", options).add_to(m)
```
--------------------------------
### ImageOverlay from Disk
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/raster_layers/image_overlay.md
Use this to display a static image file from your local disk. Ensure the image is in Mercator projection format. The 'bounds' parameter defines the geographic area where the image will be placed.
```python
import os
import folium
m = folium.Map([0, 0], zoom_start=2)
image_filepath = os.path.join("..", "..", "_static", "folium_logo.png")
img = folium.raster_layers.ImageOverlay(
name="Folium logo",
image=image_filepath,
bounds=[[-50, -45], [50, 45]],
opacity=0.6,
interactive=True,
cross_origin=False,
zindex=1,
)
folium.Popup("I am an image").add_to(img)
img.add_to(m)
folium.LayerControl().add_to(m)
m
```
--------------------------------
### Configure vector tile layer styles
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/vector_tiles.md
Create a dictionary to map specific vector tile layer names to their corresponding styles. Empty lists indicate default styling or no specific styling applied.
```python
vectorTileLayerStyles = {}
vectorTileLayerStyles["aerodrome_label"] = []
vectorTileLayerStyles["aeroway"] = []
vectorTileLayerStyles["area_name"] = []
vectorTileLayerStyles["boundary"] = styles["admin"]
vectorTileLayerStyles["building"] = []
vectorTileLayerStyles["building_ln"] = []
vectorTileLayerStyles["construct"] = []
vectorTileLayerStyles["contour_line"] = []
vectorTileLayerStyles["landcover"] = styles["landcover"]
vectorTileLayerStyles["landuse"] = styles["landuse"]
vectorTileLayerStyles["mountain_peak"] = []
vectorTileLayerStyles["park"] = styles["park"]
vectorTileLayerStyles["place"] = []
vectorTileLayerStyles["poi"] = []
vectorTileLayerStyles["spot_elevation"] = []
vectorTileLayerStyles["transportation"] = styles["road"]
vectorTileLayerStyles["transportation_name"] = []
vectorTileLayerStyles["water"] = styles["water"]
vectorTileLayerStyles["waterway"] = styles["water"]
vectorTileLayerStyles["water_name"] = []
```
--------------------------------
### Create PolyLine from Encoded String
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Example of creating a PolyLine from an encoded string using the PolyLineFromEncoded plugin and adding it to a map.
```python
>>> from folium import Map
>>> from folium.plugins import PolyLineFromEncoded
>>> m = Map()
>>> encoded = r"_p~iF~cn~U_ulLn{vA_mqNvxq`@"
>>> PolyLineFromEncoded(encoded=encoded, color="green").add_to(m)
```
--------------------------------
### Import necessary libraries
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/vector_tiles.md
Import the VectorGridProtobuf plugin and the folium library.
```python
from folium.plugins import VectorGridProtobuf
import folium
```
--------------------------------
### Basic MarkerCluster Usage
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/marker_cluster.md
Demonstrates how to initialize a map and add a MarkerCluster to it, then add individual markers to the cluster. This is useful for displaying a moderate number of markers.
```python
import folium
from folium.plugins import MarkerCluster
m = folium.Map(location=[44, -73], zoom_start=5)
marker_cluster = MarkerCluster().add_to(m)
folium.Marker(
location=[40.67, -73.94],
popup="Add popup text here.",
icon=folium.Icon(color="green", icon="ok-sign"),
).add_to(marker_cluster)
folium.Marker(
location=[44.67, -73.94],
popup="Add popup text here.",
icon=folium.Icon(color="red", icon="remove-sign"),
).add_to(marker_cluster)
folium.Marker(
location=[44.67, -71.94],
popup="Add popup text here.",
icon=None,
).add_to(marker_cluster)
m
```
--------------------------------
### Change MiniMap Tile Layer
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/mini_map.md
Customize the tile layer used for the MiniMap. 'Cartodb dark_matter' is an example of an alternative tile layer.
```python
m = folium.Map(location=(30, 20), zoom_start=4)
MiniMap(tile_layer="Cartodb dark_matter").add_to(m)
m
```
--------------------------------
### Load GeoJSON Data
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/search.md
Loads US states and populated places GeoJSON data from URLs using GeoPandas. Ensure GeoPandas is installed.
```python
import geopandas
states = geopandas.read_file(
"https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json",
driver="GeoJSON",
)
cities = geopandas.read_file(
"https://d2ad6craft/naturalearth-3.3.0/ne_50m_populated_places_simple.geojson",
driver="GeoJSON",
)
```
--------------------------------
### Custom Icon with Image and Shadow
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/ui_elements/icons.md
Shows how to create a custom icon using an image file for the icon and another for its shadow. This allows for highly personalized marker appearances.
```python
import folium
m = folium.Map(location=[45.3288, -121.6625], zoom_start=12)
url = "https://leafletjs.com/examples/custom-icons/{}".format
icon_image = url("leaf-red.png")
shadow_image = url("leaf-shadow.png")
icon = folium.CustomIcon(
icon_image,
icon_size=(38, 95),
icon_anchor=(22, 94),
shadow_image=shadow_image,
shadow_size=(50, 64),
shadow_anchor=(4, 62),
popup_anchor=(-3, -76),
)
folium.Marker(
location=[45.3288, -121.6625], icon=icon, popup="Mt. Hood Meadows"
).add_to(m)
m
```
--------------------------------
### Display GeoJSON Data from GeoPandas
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/geojson/geojson.md
Load GeoJSON data into a GeoPandas DataFrame and then add it to a Folium map. Ensure GeoPandas is installed and imported.
```python
import geopandas
gdf = geopandas.read_file(url)
m = folium.Map([43, -100], zoom_start=4)
folium.GeoJson(
gdf,
).add_to(m)
m
```
--------------------------------
### Add GeoJsonPopup to GeoJson layer
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Example of adding a `GeoJsonPopup` to an existing GeoJson layer. This popup will display the 'NAME' property of each feature without labels.
```python
gjson = folium.GeoJson(gdf).add_to(m)
folium.features.GeoJsonPopup(fields=['NAME'],
: labels=False
).add_to(gjson)
```
--------------------------------
### Add Control to Map
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Add a Leaflet Control object to a Folium map. This example demonstrates adding a zoom control to the top-left position of the map.
```python
>>> import folium
>>> from folium.features import Control, Marker
>>> from folium.plugins import Geocoder
```
```python
>>> m = folium.Map(
... location=[46.603354, 1.8883335], attr=None, zoom_control=False, zoom_start=5
... )
>>> Control("Zoom", position="topleft").add_to(m)
```
--------------------------------
### Initialize Map with OpenStreetMap Tiles
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/raster_layers/tiles.md
Creates a Folium map centered on specific coordinates and uses OpenStreetMap as the base tile layer. Requires importing the folium library.
```python
import folium
lon, lat = -38.625, -12.875
zoom_start = 8
```
```python
folium.Map(location=[lat, lon], tiles="OpenStreetMap", zoom_start=zoom_start)
```
--------------------------------
### Assign Weights to Data Points
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/heatmap_with_time.md
Assigns a weight between 0 and 1 to each data point, controlling its intensity on the heatmap. The weights increase over time in this example.
```python
time_ = 0
N = len(data)
itensify_factor = 30
for time_entry in data:
time_ = time_+1
for row in time_entry:
weight = min(np.random.uniform()*(time_/(N))*itensify_factor, 1)
row.append(weight)
```
--------------------------------
### Create and Add FeatureGroupSubGroups
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/featuregroup_subgroup.md
Demonstrates how to create a main FeatureGroup and then add nested FeatureGroupSubGroups to it. Markers can then be added to these subgroups for organized display and control.
```python
import folium
import folium.plugins
m = folium.Map(location=[0, 0], zoom_start=6)
fg = folium.FeatureGroup(name="groups")
m.add_child(fg)
g1 = folium.plugins.FeatureGroupSubGroup(fg, "group1")
m.add_child(g1)
g2 = folium.plugins.FeatureGroupSubGroup(fg, "group2")
m.add_child(g2)
folium.Marker([-1, -1]).add_to(g1)
folium.Marker([1, 1]).add_to(g1)
folium.Marker([-1, 1]).add_to(g2)
folium.Marker([1, -1]).add_to(g2)
folium.LayerControl(collapsed=False).add_to(m)
m
```
--------------------------------
### Initialize Map with CartoDB Positron Tiles
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/raster_layers/tiles.md
Renders a Folium map using the CartoDB Positron tileset. Ensure the folium library is imported and coordinates/zoom level are defined.
```python
folium.Map(location=[lat, lon], tiles="Cartodb Positron", zoom_start=zoom_start)
```
--------------------------------
### Add a PolyLine to a Folium Map
Source: https://github.com/python-visualization/folium/blob/main/docs/getting_started.md
Draw a PolyLine on the map to represent linear features like trails or roads. This example shows a coastal trail.
```python
m = folium.Map(location=[-71.38, -73.9], zoom_start=11)
trail_coordinates = [
(-71.351871840295871, -73.655963711222626),
(-71.374144382613707, -73.719861619751498),
(-71.391042575973145, -73.784922248007007),
(-71.400964450973134, -73.851042243124397),
(-71.402411391077322, -74.050048183880477),
]
folium.PolyLine(trail_coordinates, tooltip="Coast").add_to(m)
m
```
--------------------------------
### folium.vector_layers.Circle
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Class for drawing circle overlays on a map. It’s an approximation and starts to diverge from a real circle closer to the poles (due to projection distortion).
```APIDOC
## Class: folium.vector_layers.Circle
### Description
Class for drawing circle overlays on a map. It’s an approximation and starts to diverge from a real circle closer to the poles (due to projection distortion).
### Parameters
* **location** (*tuple* *[**float* *,* *float* *]*) – Latitude and Longitude pair (Northing, Easting)
* **radius** (*float*) – Radius of the circle, in meters.
* **popup** (*string* *or* *folium.Popup* *,* *default None*) – Input text or visualization for object displayed when clicking.
* **tooltip** (*str* *or* *folium.Tooltip* *,* *default None*) – Display a text when hovering over the object.
* **kwargs** – Other valid (possibly inherited) options. See: [https://leafletjs.com/reference.html#circle](https://leafletjs.com/reference.html#circle)
```
--------------------------------
### Create Map with Initial Timestamp
Source: https://github.com/python-visualization/folium/blob/main/docs/user_guide/plugins/timeslider_choropleth.md
Initialize the time slider at a specific timestamp using the `init_timestamp` parameter. Use -1 to start at the last timestamp.
```python
m = folium.Map([0, 0], zoom_start=2)
TimeSliderChoropleth(
gdf.to_json(),
styledict=styledict,
init_timestamp=-1,
).add_to(m)
m
```
--------------------------------
### Style TopoJson Features Conditionally
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Apply a custom style function to TopoJson features. This example colors features green, except for 'Alabama' which is colored blue.
```python
style_function = lambda x: {
"fillColor": (
"#0000ff" if x["properties"]["name"] == "Alabama" else "#00ff00"
)
}
TopoJson(topo_json, "object.myobject", style_function=style_function)
```
--------------------------------
### Instantiate GeoJson with different data inputs
Source: https://github.com/python-visualization/folium/blob/main/docs/reference.md
Shows how to create a GeoJson layer by providing a filename, a dictionary, or a string. The `embed` parameter controls whether the GeoJson data is embedded directly into the HTML.
```python
>>> # Providing filename that shall be embedded.
>>> GeoJson("foo.json")
```
```python
>>> # Providing filename that shall not be embedded.
>>> GeoJson("foo.json", embed=False)
```
```python
>>> # Providing dict.
>>> GeoJson(json.load(open("foo.json")))
```
```python
>>> # Providing string.
>>> GeoJson(open("foo.json").read())
```
--------------------------------
### Create a Choropleth Map with Folium
Source: https://github.com/python-visualization/folium/blob/main/docs/getting_started.md
Generate a Choropleth map by binding data from a Pandas DataFrame to GeoJSON geometries. This example visualizes US unemployment rates.
```python
import pandas
state_geo = requests.get(
"https://raw.githubusercontent.com/python-visualization/folium-example-data/main/us_states.json"
).json()
state_data = pandas.read_csv(
"https://raw.githubusercontent.com/python-visualization/folium-example-data/main/us_unemployment_oct_2012.csv"
)
m = folium.Map(location=[48, -102], zoom_start=3)
folium.Choropleth(
geo_data=state_geo,
name="choropleth",
data=state_data,
columns=["State", "Unemployment"],
key_on="feature.id",
fill_color="YlGn",
fill_opacity=0.7,
line_opacity=0.2,
legend_name="Unemployment Rate (%)",
).add_to(m)
folium.LayerControl().add_to(m)
m
```
--------------------------------
### Add GeoJSON Overlay to Folium Map
Source: https://github.com/python-visualization/folium/blob/main/docs/getting_started.md
Overlay GeoJSON data onto a Folium map. This example fetches world country data and displays it with a name.
```python
import requests
m = folium.Map(tiles="cartodbpositron")
geojson_data = requests.get(
"https://raw.githubusercontent.com/python-visualization/folium-example-data/main/world_countries.json"
).json()
folium.GeoJson(geojson_data, name="hello world").add_to(m)
folium.LayerControl().add_to(m)
m
```