folium

Make beautiful, interactive maps with Python and Leaflet.js

class folium.folium.GlobalSwitches(no_touch=False, disable_3d=False)

Bases: branca.element.Element

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

Bases: folium.elements.JSCSSMixin, branca.element.MacroElement

Create a Map with Folium and Leaflet.js

Generate a base map of given width and height with either default tilesets or a custom tileset URL. The following tilesets are built-in to Folium. Pass any of the following to the “tiles” keyword:

  • “OpenStreetMap”

  • “Mapbox Bright” (Limited levels of zoom for free tiles)

  • “Mapbox Control Room” (Limited levels of zoom for free tiles)

  • “Stamen” (Terrain, Toner, and Watercolor)

  • “Cloudmade” (Must pass API key)

  • “Mapbox” (Must pass API key)

  • “CartoDB” (positron and dark_matter)

You can pass a custom tileset to Folium by passing a Leaflet-style URL to the tiles parameter: http://{s}.yourtiles.com/{z}/{x}/{y}.png.

You can find a list of free tile providers here: http://leaflet-extras.github.io/leaflet-providers/preview/. Be sure to check their terms and conditions and to provide attribution with the attr keyword.

Parameters
  • location (tuple or list, default None) – Latitude and Longitude of Map (Northing, Easting).

  • width (pixel int or percentage string (default: '100%')) – Width of the map.

  • height (pixel int or percentage string (default: '100%')) – Height of the map.

  • tiles (str, default 'OpenStreetMap') – Map tileset to use. Can choose from a list of built-in tiles, pass a custom URL or pass None to create a map without tiles. For more advanced tile layer options, use the TileLayer class.

  • min_zoom (int, default 0) – Minimum allowed zoom level for the tile layer that is created.

  • max_zoom (int, default 18) – Maximum allowed zoom level for the tile layer that is created.

  • zoom_start (int, default 10) – Initial zoom level for the map.

  • attr (string, default None) – Map tile attribution; only required if passing custom tile URL.

  • crs (str, default 'EPSG3857') – Defines coordinate reference systems for projecting geographical points into pixel (screen) coordinates and back. You can use Leaflet’s values : * EPSG3857 : The most common CRS for online maps, used by almost all free and commercial tile providers. Uses Spherical Mercator projection. Set in by default in Map’s crs option. * EPSG4326 : A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. * EPSG3395 : Rarely used by some commercial tile providers. Uses Elliptical Mercator projection. * Simple : A simple CRS that maps longitude and latitude into x and y directly. May be used for maps of flat surfaces (e.g. game maps). Note that the y axis should still be inverted (going from bottom to top).

  • control_scale (bool, default False) – Whether to add a control scale on the map.

  • prefer_canvas (bool, default False) – Forces Leaflet to use the Canvas back-end (if available) for vector layers instead of SVG. This can increase performance considerably in some cases (e.g. many thousands of circle markers on the map).

  • no_touch (bool, default False) – Forces Leaflet to not use touch events even if it detects them.

  • disable_3d (bool, default False) – Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning (which may cause glitches in some rare environments) even if they’re supported.

  • zoom_control (bool, default True) – Display zoom controls on the map.

  • **kwargs – Additional keyword arguments are passed to Leaflets Map class: https://leafletjs.com/reference-1.6.0.html#map

Returns

Return type

Folium Map Object

Examples

>>> m = folium.Map(location=[45.523, -122.675], width=750, height=500)
>>> m = folium.Map(location=[45.523, -122.675], tiles='cartodb positron')
>>> 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'
...)
choropleth(*args, **kwargs)

Call the Choropleth class with the same arguments.

This method may be deleted after a year from now (Nov 2018).

default_css = [('leaflet_css', 'https://cdn.jsdelivr.net/npm/leaflet@1.6.0/dist/leaflet.css'), ('bootstrap_css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'), ('bootstrap_theme_css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css'), ('awesome_markers_font_css', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css'), ('awesome_markers_css', 'https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.css'), ('awesome_rotate_css', 'https://cdn.jsdelivr.net/gh/python-visualization/folium/folium/templates/leaflet.awesome.rotate.min.css')]
default_js = [('leaflet', 'https://cdn.jsdelivr.net/npm/leaflet@1.6.0/dist/leaflet.js'), ('jquery', 'https://code.jquery.com/jquery-1.12.4.min.js'), ('bootstrap', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js'), ('awesome_markers', 'https://cdnjs.cloudflare.com/ajax/libs/Leaflet.awesome-markers/2.0.2/leaflet.awesome-markers.js')]
fit_bounds(bounds, padding_top_left=None, padding_bottom_right=None, padding=None, max_zoom=None)

Fit the map to contain a bounding box with the maximum zoom level possible.

Parameters
  • bounds (list of (latitude, longitude) points) – Bounding box specified as two points [southwest, northeast]

  • padding_top_left ((x, y) point, default None) – Padding in the top left corner. Useful if some elements in the corner, such as controls, might obscure objects you’re zooming to.

  • padding_bottom_right ((x, y) point, default None) – Padding in the bottom right corner.

  • padding ((x, y) point, default None) – Equivalent to setting both top left and bottom right padding to the same value.

  • max_zoom (int, default None) – Maximum zoom to be used.

Examples

>>> m.fit_bounds([[52.193636, -2.221575], [52.636878, -1.139759]])
keep_in_front(*args)

Pass one or multiple layers that must stay in front.

The ordering matters, the last one is put on top.

Parameters

*args – Variable length argument list. Any folium object that counts as an overlay. For example FeatureGroup or TileLayer. Does not work with markers, for those use z_index_offset.

render(**kwargs)

Renders the HTML representation of the element.

map

Classes for drawing maps.

class folium.map.CustomPane(name, z_index=625, pointer_events=False)

Bases: branca.element.MacroElement

Creates a custom pane to hold map elements.

Behavior is as in https://leafletjs.com/examples/map-panes/

Parameters
  • name (string) – Name of the custom pane. Other map elements can be added to the pane by specifying the ‘pane’ kwarg when constructing them.

  • z_index (int or string, default 625) – The z-index that will be associated with the pane, and will determine which map elements lie over/under it. The default (625) corresponds to between markers and tooltips. Default panes and z-indexes can be found at https://leafletjs.com/reference-1.6.0.html#map-pane

  • pointer_events (bool, default False) – Whether or not layers in the pane should interact with the cursor. Setting to False will prevent interfering with pointer events associated with lower layers.

class folium.map.FeatureGroup(name=None, overlay=True, control=True, show=True, **kwargs)

Bases: folium.map.Layer

Create a FeatureGroup layer ; you can put things in it and handle them as a single layer. For example, you can add a LayerControl to tick/untick the whole group.

Parameters
  • name (str, default None) – The name of the featureGroup layer. It will be displayed in the LayerControl. If None get_name() will be called to get the technical (ugly) name.

  • overlay (bool, default True) – Whether your layer will be an overlay (ticked with a check box in LayerControls) or a base layer (ticked with a radio button).

  • control (bool, default True) – Whether the layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • **kwargs – Additional (possibly inherited) options. See https://leafletjs.com/reference-1.6.0.html#featuregroup

class folium.map.FitBounds(bounds, padding_top_left=None, padding_bottom_right=None, padding=None, max_zoom=None)

Bases: branca.element.MacroElement

Fit the map to contain a bounding box with the maximum zoom level possible.

Parameters
  • bounds (list of (latitude, longitude) points) – Bounding box specified as two points [southwest, northeast]

  • padding_top_left ((x, y) point, default None) – Padding in the top left corner. Useful if some elements in the corner, such as controls, might obscure objects you’re zooming to.

  • padding_bottom_right ((x, y) point, default None) – Padding in the bottom right corner.

  • padding ((x, y) point, default None) – Equivalent to setting both top left and bottom right padding to the same value.

  • max_zoom (int, default None) – Maximum zoom to be used.

class folium.map.Icon(color='blue', icon_color='white', icon='info-sign', angle=0, prefix='glyphicon', **kwargs)

Bases: branca.element.MacroElement

Creates an Icon object that will be rendered using Leaflet.awesome-markers.

Parameters
  • color (str, default 'blue') –

    The color of the marker. You can use:

    [‘red’, ‘blue’, ‘green’, ‘purple’, ‘orange’, ‘darkred’,

    ’lightred’, ‘beige’, ‘darkblue’, ‘darkgreen’, ‘cadetblue’, ‘darkpurple’, ‘white’, ‘pink’, ‘lightblue’, ‘lightgreen’, ‘gray’, ‘black’, ‘lightgray’]

  • icon_color (str, default 'white') – The color of the drawing on the marker. You can use colors above, or an html color code.

  • icon (str, default 'info-sign') – The name of the marker sign. See Font-Awesome website to choose yours. Warning : depending on the icon you choose you may need to adapt the prefix as well.

  • angle (int, default 0) – The icon will be rotated by this amount of degrees.

  • prefix (str, default 'glyphicon') – The prefix states the source of the icon. ‘fa’ for font-awesome or ‘glyphicon’ for bootstrap 3.

  • https (//github.com/lvoogdt/Leaflet.awesome-markers) –

color_options = {'beige', 'black', 'blue', 'cadetblue', 'darkblue', 'darkgreen', 'darkpurple', 'darkred', 'gray', 'green', 'lightblue', 'lightgray', 'lightgreen', 'lightred', 'orange', 'pink', 'purple', 'red', 'white'}
class folium.map.Layer(name=None, overlay=False, control=True, show=True)

Bases: branca.element.MacroElement

An abstract class for everything that is a Layer on the map. It will be used to define whether an object will be included in LayerControls.

Parameters
  • name (string, default None) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default False) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

class folium.map.LayerControl(position='topright', collapsed=True, autoZIndex=True, **kwargs)

Bases: branca.element.MacroElement

Creates a LayerControl object to be added on a folium map.

This object should be added to a Map object. Only Layer children of Map are included in the layer control.

Parameters
  • position (str) – The position of the control (one of the map corners), can be ‘topleft’, ‘topright’, ‘bottomleft’ or ‘bottomright’ default: ‘topright’

  • collapsed (bool, default True) – If true the control will be collapsed into an icon and expanded on mouse hover or touch.

  • autoZIndex (bool, default True) – If true the control assigns zIndexes in increasing order to all of its layers so that the order is preserved when switching them on/off.

  • **kwargs – Additional (possibly inherited) options. See https://leafletjs.com/reference-1.6.0.html#control-layers

render(**kwargs)

Renders the HTML representation of the element.

reset()
class folium.map.Marker(location=None, popup=None, tooltip=None, icon=None, draggable=False, **kwargs)

Bases: branca.element.MacroElement

Create a simple stock Leaflet marker on the map, with optional popup text or Vincent visualization.

Parameters
  • location (tuple or list) – Latitude and Longitude of Marker (Northing, Easting)

  • popup (string or folium.Popup, default None) – Label for the Marker; either an escaped HTML string to initialize folium.Popup or a folium.Popup instance.

  • tooltip (str or folium.Tooltip, default None) – Display a text when hovering over the object.

  • icon (Icon plugin) – the Icon plugin to use to render the marker.

  • draggable (bool, default False) – Set to True to be able to drag the marker around the map.

Returns

Return type

Marker names and HTML in obj.template_vars

Examples

>>> Marker(location=[45.5, -122.3], popup='Portland, OR')
>>> Marker(location=[45.5, -122.3], popup=Popup('Portland, OR'))
# If the popup label has characters that need to be escaped in HTML
>>> Marker(location=[45.5, -122.3],
...        popup=Popup('Mom & Pop Arrow Shop >>', parse_html=True))
render()

Renders the HTML representation of the element.

class folium.map.Popup(html=None, parse_html=False, max_width='100%', show=False, sticky=False, **kwargs)

Bases: branca.element.Element

Create a Popup instance that can be linked to a Layer.

Parameters
  • html (string or Element) – Content of the Popup.

  • parse_html (bool, default False) – True if the popup is a template that needs to the rendered first.

  • max_width (int for pixels or text for percentages, default '100%') – The maximal width of the popup.

  • show (bool, default False) – True renders the popup open on page load.

  • sticky (bool, default False) – True prevents map and other popup clicks from closing.

render(**kwargs)

Renders the HTML representation of the element.

class folium.map.Tooltip(text, style=None, sticky=True, **kwargs)

Bases: branca.element.MacroElement

Create a tooltip that shows text when hovering over its parent object.

Parameters
  • text (str) – String to display as a tooltip on the object. If the argument is of a different type it will be converted to str.

  • style (str, default None.) – HTML inline style properties like font and colors. Will be applied to a div with the text in it.

  • sticky (bool, default True) – Whether the tooltip should follow the mouse.

  • **kwargs – These values will map directly to the Leaflet Options. More info available here: https://leafletjs.com/reference-1.6.0#tooltip

parse_options(kwargs)

Validate the provided kwargs and return options as json string.

valid_options = {'attribution': (<class 'str'>,), 'className': (<class 'str'>,), 'direction': (<class 'str'>,), 'interactive': (<class 'bool'>,), 'offset': (<class 'tuple'>,), 'opacity': (<class 'float'>, <class 'int'>), 'pane': (<class 'str'>,), 'permanent': (<class 'bool'>,), 'sticky': (<class 'bool'>,)}

Vector Layers

Wraps leaflet Polyline, Polygon, Rectangle, Circle, and CircleMarker

class folium.vector_layers.BaseMultiLocation(locations, popup=None, tooltip=None)

Bases: branca.element.MacroElement

Base class for vector classes with multiple coordinates.

Not for direct consumption

class folium.vector_layers.Circle(location=None, radius=50, popup=None, tooltip=None, **kwargs)

Bases: folium.map.Marker

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

See folium.vector_layers.path_options() for the Path options.

Parameters
  • location (tuple[float, float]) – Latitude and Longitude pair (Northing, Easting)

  • 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.

  • radius (float) – Radius of the circle, in meters.

  • **kwargs – Other valid (possibly inherited) options. See: https://leafletjs.com/reference-1.6.0.html#circle

class folium.vector_layers.CircleMarker(location=None, radius=10, popup=None, tooltip=None, **kwargs)

Bases: folium.map.Marker

A circle of a fixed size with radius specified in pixels.

See folium.vector_layers.path_options() for the Path options.

Parameters
  • location (tuple[float, float]) – Latitude and Longitude pair (Northing, Easting)

  • 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.

  • radius (float, default 10) – Radius of the circle marker, in pixels.

  • **kwargs – Other valid (possibly inherited) options. See: https://leafletjs.com/reference-1.6.0.html#circlemarker

class folium.vector_layers.PolyLine(locations, popup=None, tooltip=None, **kwargs)

Bases: folium.vector_layers.BaseMultiLocation

Draw polyline overlays on a map.

See folium.vector_layers.path_options() for the Path options.

Parameters
  • locations (list of points (latitude, longitude)) – Latitude and Longitude of line (Northing, Easting)

  • popup (str 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.

  • smooth_factor (float, default 1.0) – How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation.

  • no_clip (Bool, default False) – Disable polyline clipping.

  • **kwargs – Other valid (possibly inherited) options. See: https://leafletjs.com/reference-1.6.0.html#polyline

class folium.vector_layers.Polygon(locations, popup=None, tooltip=None, **kwargs)

Bases: folium.vector_layers.BaseMultiLocation

Draw polygon overlays on a map.

See folium.vector_layers.path_options() for the Path options.

Parameters
  • locations (list of points (latitude, longitude)) – Latitude and Longitude of line (Northing, Easting)

  • 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-1.6.0.html#polygon

class folium.vector_layers.Rectangle(bounds, popup=None, tooltip=None, **kwargs)

Bases: folium.vector_layers.BaseMultiLocation

Draw rectangle overlays on a map.

See folium.vector_layers.path_options() for the Path options.

Parameters
  • bounds (list of points (latitude, longitude)) – Latitude and Longitude of line (Northing, Easting)

  • 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-1.6.0.html#rectangle

folium.vector_layers.path_options(line=False, radius=False, **kwargs)

Contains options and constants shared between vector overlays (Polygon, Polyline, Circle, CircleMarker, and Rectangle).

Parameters

Raster Layers

Wraps leaflet TileLayer, WmsTileLayer (TileLayer.WMS), ImageOverlay, and VideoOverlay

class folium.raster_layers.ImageOverlay(image, bounds, origin='upper', colormap=None, mercator_project=False, pixelated=True, name=None, overlay=True, control=True, show=True, **kwargs)

Bases: folium.map.Layer

Used to load and display a single image over specific bounds of the map, implements ILayer interface.

Parameters
  • image (string, file or array-like object) – The data you want to draw on the map. * If string, it will be written directly in the output file. * If file, it’s content will be converted as embedded in the output file. * If array-like, it will be converted to PNG base64 string and embedded in the output.

  • bounds (list) –

    Image bounds on the map in the form

    [[lat_min, lon_min], [lat_max, lon_max]]

  • opacity (float, default Leaflet's default (1.0)) –

  • alt (string, default Leaflet's default ('')) –

  • origin (['upper' | 'lower'], optional, default 'upper') – Place the [0,0] index of the array in the upper left or lower left corner of the axes.

  • colormap (callable, used only for mono image.) – Function of the form [x -> (r,g,b)] or [x -> (r,g,b,a)] for transforming a mono image into RGB. It must output iterables of length 3 or 4, with values between 0 and 1. Hint: you can use colormaps from matplotlib.cm.

  • mercator_project (bool, default False.) – Used only for array-like image. Transforms the data to project (longitude, latitude) coordinates to the Mercator projection. Beware that this will only work if image is an array-like object.

  • pixelated (bool, default True) – Sharp sharp/crips (True) or aliased corners (False).

  • name (string, default None) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default True) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • https (See) –

  • options.

render(**kwargs)

Renders the HTML representation of the element.

class folium.raster_layers.TileLayer(tiles='OpenStreetMap', min_zoom=0, max_zoom=18, max_native_zoom=None, attr=None, detect_retina=False, name=None, overlay=False, control=True, show=True, no_wrap=False, subdomains='abc', tms=False, opacity=1, **kwargs)

Bases: folium.map.Layer

Create a tile layer to append on a Map.

Parameters
  • tiles (str, default 'OpenStreetMap') –

    Map tileset to use. Can choose from this list of built-in tiles:
    • ”OpenStreetMap”

    • ”Stamen Terrain”, “Stamen Toner”, “Stamen Watercolor”

    • ”CartoDB positron”, “CartoDB dark_matter”

    You can pass a custom tileset to Folium by passing a Leaflet-style URL to the tiles parameter: http://{s}.yourtiles.com/{z}/{x}/{y}.png.

    You can find a list of free tile providers here: http://leaflet-extras.github.io/leaflet-providers/preview/. Be sure to check their terms and conditions and to provide attribution with the attr keyword.

  • min_zoom (int, default 0) – Minimum allowed zoom level for this tile layer.

  • max_zoom (int, default 18) – Maximum allowed zoom level for this tile layer.

  • max_native_zoom (int, default None) – The highest zoom level at which the tile server can provide tiles. If provided you can zoom in past this level. Else tiles will turn grey.

  • attr (string, default None) – Map tile attribution; only required if passing custom tile URL.

  • detect_retina (bool, default False) – If true and user is on a retina display, it will request four tiles of half the specified size and a bigger zoom level in place of one to utilize the high resolution.

  • name (string, default None) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default False) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • subdomains (list of strings, default ['abc']) – Subdomains of the tile service.

  • tms (bool, default False) – If true, inverses Y axis numbering for tiles (turn this on for TMS services).

  • opacity (float, default 1) – Sets the opacity for the layer.

  • **kwargs (additional keyword arguments) – Other keyword arguments are passed as options to the Leaflet tileLayer object.

class folium.raster_layers.VideoOverlay(video_url, bounds, autoplay=True, loop=True, name=None, overlay=True, control=True, show=True, **kwargs)

Bases: folium.map.Layer

Used to load and display a video over the map.

Parameters
  • video_url (str) – URL of the video

  • bounds (list) –

    Video bounds on the map in the form

    [[lat_min, lon_min], [lat_max, lon_max]]

  • autoplay (bool, default True) –

  • loop (bool, default True) –

  • name (string, default None) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default True) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • **kwargs – Other valid (possibly inherited) options. See: https://leafletjs.com/reference-1.6.0.html#videooverlay

class folium.raster_layers.WmsTileLayer(url, layers, styles='', fmt='image/jpeg', transparent=False, version='1.1.1', attr='', name=None, overlay=True, control=True, show=True, **kwargs)

Bases: folium.map.Layer

Creates a Web Map Service (WMS) layer.

Parameters
  • url (str) – The url of the WMS server.

  • layers (str) – Comma-separated list of WMS layers to show.

  • styles (str, optional) – Comma-separated list of WMS styles.

  • fmt (str, default 'image/jpeg') – The format of the service output. Ex: ‘image/png’

  • transparent (bool, default False) – Whether the layer shall allow transparency.

  • version (str, default '1.1.1') – Version of the WMS service to use.

  • attr (str, default '') – The attribution of the service. Will be displayed in the bottom right corner.

  • name (string, optional) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default True) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • **kwargs (additional keyword arguments) – Passed through to the underlying tileLayer.wms object and can be used for setting extra tileLayer.wms parameters or as extra parameters in the WMS request.

  • https (See) –

Extra Features

Leaflet GeoJson and miscellaneous features.

class folium.features.Choropleth(geo_data, data=None, columns=None, key_on=None, bins=6, fill_color=None, nan_fill_color='black', fill_opacity=0.6, nan_fill_opacity=None, line_color='black', line_weight=1, line_opacity=1, name=None, legend_name='', overlay=True, control=True, show=True, topojson=None, smooth_factor=None, highlight=None, **kwargs)

Bases: folium.map.FeatureGroup

Apply a GeoJSON overlay to the map.

Plot a GeoJSON overlay on the base map. There is no requirement to bind data (passing just a GeoJSON plots a single-color overlay), but there is a data binding option to map your columnar data to different feature objects with a color scale.

If data is passed as a Pandas DataFrame, the “columns” and “key-on” keywords must be included, the first to indicate which DataFrame columns to use, the second to indicate the layer in the GeoJSON on which to key the data. The ‘columns’ keyword does not need to be passed for a Pandas series.

Colors are generated from color brewer (http://colorbrewer2.org/) sequential palettes. By default, linear binning is used between the min and the max of the values. Custom binning can be achieved with the bins parameter.

TopoJSONs can be passed as “geo_data”, but the “topojson” keyword must also be passed with the reference to the topojson objects to convert. See the topojson.feature method in the TopoJSON API reference: https://github.com/topojson/topojson/wiki/API-Reference

Parameters
  • geo_data (string/object) – URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON geometries

  • data (Pandas DataFrame or Series, default None) – Data to bind to the GeoJSON.

  • columns (dict or tuple, default None) – If the data is a Pandas DataFrame, the columns of data to be bound. Must pass column 1 as the key, and column 2 the values.

  • key_on (string, default None) – Variable in the geo_data GeoJSON file to bind the data to. Must start with ‘feature’ and be in JavaScript objection notation. Ex: ‘feature.id’ or ‘feature.properties.statename’.

  • bins (int or sequence of scalars or str, default 6) – If bins is an int, it defines the number of equal-width bins between the min and the max of the values. If bins is a sequence, it directly defines the bin edges. For more information on this parameter, have a look at numpy.histogram function.

  • fill_color (string, optional) – Area fill color, defaults to blue. Can pass a hex code, color name, or if you are binding data, one of the following color brewer palettes: ‘BuGn’, ‘BuPu’, ‘GnBu’, ‘OrRd’, ‘PuBu’, ‘PuBuGn’, ‘PuRd’, ‘RdPu’, ‘YlGn’, ‘YlGnBu’, ‘YlOrBr’, and ‘YlOrRd’.

  • nan_fill_color (string, default 'black') – Area fill color for nan or missing values. Can pass a hex code, color name.

  • fill_opacity (float, default 0.6) – Area fill opacity, range 0-1.

  • nan_fill_opacity (float, default fill_opacity) – Area fill opacity for nan or missing values, range 0-1.

  • line_color (string, default 'black') – GeoJSON geopath line color.

  • line_weight (int, default 1) – GeoJSON geopath line weight.

  • line_opacity (float, default 1) – GeoJSON geopath line opacity, range 0-1.

  • legend_name (string, default empty string) – Title for data legend.

  • topojson (string, default None) – If using a TopoJSON, passing “objects.yourfeature” to the topojson keyword argument will enable conversion to GeoJSON.

  • smooth_factor (float, default None) – How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. Leaflet defaults to 1.0.

  • highlight (boolean, default False) – Enable highlight functionality when hovering over a GeoJSON area.

  • name (string, optional) – The name of the layer, as it will appear in LayerControls

  • overlay (bool, default True) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

Returns

Return type

GeoJSON data layer in obj.template_vars

Examples

>>> Choropleth(geo_data='us-states.json', line_color='blue',
...            line_weight=3)
>>> Choropleth(geo_data='geo.json', data=df,
...            columns=['Data 1', 'Data 2'],
...            key_on='feature.properties.myvalue',
...            fill_color='PuBu',
...            bins=[0, 20, 30, 40, 50, 60])
>>> Choropleth(geo_data='countries.json',
...            topojson='objects.countries')
>>> Choropleth(geo_data='geo.json', data=df,
...            columns=['Data 1', 'Data 2'],
...            key_on='feature.properties.myvalue',
...            fill_color='PuBu',
...            bins=[0, 20, 30, 40, 50, 60],
...            highlight=True)
render(**kwargs)

Render the GeoJson/TopoJson and color scale objects.

class folium.features.ClickForMarker(popup=None)

Bases: branca.element.MacroElement

When one clicks on a Map that contains a ClickForMarker, a Marker is created at the pointer’s position.

Parameters

popup (str, default None) – Text to display in the markers’ popups. If None, the popups will display the marker’s latitude and longitude.

class folium.features.ColorLine(positions, colors, colormap=None, nb_steps=12, weight=None, opacity=None, **kwargs)

Bases: folium.map.FeatureGroup

Draw data on a map with specified colors.

Parameters
  • positions (tuple or list) – The list of points latitude and longitude

  • colors (tuple or list) – The list of segments colors. It must have length equal to len(positions)-1.

  • colormap (branca.colormap.Colormap or list or tuple) – The colormap to use. If a list or tuple of colors is provided, a LinearColormap will be created from it.

  • nb_steps (int, default 12) – To have lighter output the colormap will be discretized to that number of colors.

  • opacity (float, default 1) – Line opacity, scale 0-1

  • weight (int, default 2) – Stroke weight in pixels

  • **kwargs – Further parameters available. See folium.map.FeatureGroup

Returns

Return type

A ColorLine object that you can add_to a Map.

class folium.features.CustomIcon(icon_image, icon_size=None, icon_anchor=None, shadow_image=None, shadow_size=None, shadow_anchor=None, popup_anchor=None)

Bases: folium.map.Icon

Create a custom icon, based on an image.

Parameters
  • icon_image (string, file or array-like object) – The data you want to use as an icon. * If string, it will be written directly in the output file. * If file, it’s content will be converted as embedded in the output file. * If array-like, it will be converted to PNG base64 string and embedded in the output.

  • icon_size (tuple of 2 int, optional) – Size of the icon image in pixels.

  • icon_anchor (tuple of 2 int, optional) – The coordinates of the “tip” of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker’s geographical location.

  • shadow_image (string, file or array-like object, optional) – The data for the shadow image. If not specified, no shadow image will be created.

  • shadow_size (tuple of 2 int, optional) – Size of the shadow image in pixels.

  • shadow_anchor (tuple of 2 int, optional) – The coordinates of the “tip” of the shadow relative to its top left corner (the same as icon_anchor if not specified).

  • popup_anchor (tuple of 2 int, optional) – The coordinates of the point from which popups will “open”, relative to the icon anchor.

class folium.features.DivIcon(html=None, icon_size=None, icon_anchor=None, popup_anchor=None, class_name='empty')

Bases: branca.element.MacroElement

Represents a lightweight icon for markers that uses a simple div element instead of an image.

Parameters
  • icon_size (tuple of 2 int) – Size of the icon image in pixels.

  • icon_anchor (tuple of 2 int) – The coordinates of the “tip” of the icon (relative to its top left corner). The icon will be aligned so that this point is at the marker’s geographical location.

  • popup_anchor (tuple of 2 int) – The coordinates of the point from which popups will “open”, relative to the icon anchor.

  • class_name (string) – A custom class name to assign to the icon. Leaflet defaults is ‘leaflet-div-icon’ which draws a little white square with a shadow. We set it ‘empty’ in folium.

  • html (string) – A custom HTML code to put inside the div element.

  • https (See) –

class folium.features.GeoJson(data, style_function=None, highlight_function=None, name=None, overlay=True, control=True, show=True, smooth_factor=None, tooltip=None, embed=True, popup=None, zoom_on_click=False, marker=None)

Bases: folium.map.Layer

Creates a GeoJson object for plotting into a Map.

Parameters
  • data (file, dict or str.) – The GeoJSON data you want to plot. * If file, then data will be read in the file and fully embedded in Leaflet’s JavaScript. * If dict, then data will be converted to JSON and embedded in the JavaScript. * If str, then data will be passed to the JavaScript as-is. * If __geo_interface__ is available, the __geo_interface__ dictionary will be serialized to JSON and reprojected if to_crs is available.

  • style_function (function, default None) – Function mapping a GeoJson Feature to a style dict.

  • highlight_function (function, default None) – Function mapping a GeoJson Feature to a style dict for mouse events.

  • name (string, default None) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default True) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • smooth_factor (float, default None) – How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. Leaflet defaults to 1.0.

  • tooltip (GeoJsonTooltip, Tooltip or str, default None) – Display a text when hovering over the object. Can utilize the data, see folium.GeoJsonTooltip for info on how to do that.

  • popup (GeoJsonPopup, optional) – Show a different popup for each feature by passing a GeoJsonPopup object.

  • marker (Circle, CircleMarker or Marker, optional) – If your data contains Point geometry, you can format the markers by passing a Cirle, CircleMarker or Marker object with your wanted options. The style_function and highlight_function will also target the marker object you passed.

  • embed (bool, default True) – Whether to embed the data in the html file or not. Note that disabling embedding is only supported if you provide a file link or URL.

  • zoom_on_click (bool, default False) – Set to True to enable zooming in on a geometry when clicking on it.

Examples

>>> # Providing filename that shall be embedded.
>>> GeoJson('foo.json')
>>> # Providing filename that shall not be embedded.
>>> GeoJson('foo.json', embed=False)
>>> # Providing dict.
>>> GeoJson(json.load(open('foo.json')))
>>> # Providing string.
>>> GeoJson(open('foo.json').read())
>>> # Provide a style_function that color all states green but Alabama.
>>> style_function = lambda x: {'fillColor': '#0000ff' if
...                             x['properties']['name']=='Alabama' else
...                             '#00ff00'}
>>> GeoJson(geojson, style_function=style_function)
convert_to_feature_collection()

Convert data into a FeatureCollection if it is not already.

find_identifier()

Find a unique identifier for each feature, create it if needed.

According to the GeoJSON specs a feature:
  • MAY have an ‘id’ field with a string or numerical value.

  • MUST have a ‘properties’ field. The content can be any json object or even null.

process_data(data)

Convert an unknown data input into a geojson dictionary.

render(**kwargs)

Renders the HTML representation of the element.

class folium.features.GeoJsonDetail(fields, aliases=None, labels=True, localize=False, style=None, class_name='geojsondetail')

Bases: branca.element.MacroElement

Base class for GeoJsonTooltip and GeoJsonPopup to inherit methods and template structure from. Not for direct usage.

base_template = "\n function(layer){\n let div = L.DomUtil.create('div');\n {% if this.fields %}\n let handleObject = feature=>typeof(feature)=='object' ? JSON.stringify(feature) : feature;\n let fields = {{ this.fields | tojson | safe }};\n let aliases = {{ this.aliases | tojson | safe }};\n let table = '<table>' +\n String(\n fields.map(\n (v,i)=>\n `<tr>{% if this.labels %}\n <th>${aliases[i]{% if this.localize %}.toLocaleString(){% endif %}}</th>\n {% endif %}\n <td>${handleObject(layer.feature.properties[v]){% if this.localize %}.toLocaleString(){% endif %}}</td>\n </tr>`).join(''))\n +'</table>';\n div.innerHTML=table;\n {% endif %}\n return div\n }\n "
render(**kwargs)

Renders the HTML representation of the element.

warn_for_geometry_collections()

Checks for GeoJson GeometryCollection features to warn user about incompatibility.

class folium.features.GeoJsonPopup(fields=None, aliases=None, labels=True, style='margin: auto;', class_name='foliumpopup', localize=True, **kwargs)

Bases: folium.features.GeoJsonDetail

Create a popup feature to bind to each element of a GeoJson layer based on its attributes.

Parameters
  • fields (list or tuple.) – Labels of GeoJson/TopoJson ‘properties’ or GeoPandas GeoDataFrame columns you’d like to display.

  • aliases (list/tuple of strings, same length/order as fields, default None.) – Optional aliases you’d like to display in the tooltip as field name instead of the keys of fields.

  • labels (bool, default True.) – Set to False to disable displaying the field names or aliases.

  • localize (bool, default False.) – This will use JavaScript’s .toLocaleString() to format ‘clean’ values as strings for the user’s location; i.e. 1,000,000.00 comma separators, float truncation, etc. *Available for most of JavaScript’s primitive types (any data you’ll serve into the template).

  • style (str, default None.) – HTML inline style properties like font and colors. Will be applied to a div with the text in it.

Examples

gjson = folium.GeoJson(gdf).add_to(m)

folium.features.GeoJsonPopup(fields=[‘NAME’],

labels=False ).add_to(gjson)

class folium.features.GeoJsonStyleMapper(data, feature_identifier, geojson_obj)

Bases: object

Create dicts that map styling to GeoJson features.

Used in the GeoJson class. Users don’t have to call this class directly.

get_feature_id(feature)

Return a value identifying the feature.

get_highlight_map(highlight_function)

Return a dict that maps highlight parameters to features.

get_style_map(style_function)

Return a dict that maps style parameters to features.

class folium.features.GeoJsonTooltip(fields, aliases=None, labels=True, localize=False, style=None, class_name='foliumtooltip', sticky=True, **kwargs)

Bases: folium.features.GeoJsonDetail

Create a tooltip that uses data from either geojson or topojson.

Parameters
  • fields (list or tuple.) – Labels of GeoJson/TopoJson ‘properties’ or GeoPandas GeoDataFrame columns you’d like to display.

  • aliases (list/tuple of strings, same length/order as fields, default None.) – Optional aliases you’d like to display in the tooltip as field name instead of the keys of fields.

  • labels (bool, default True.) – Set to False to disable displaying the field names or aliases.

  • localize (bool, default False.) – This will use JavaScript’s .toLocaleString() to format ‘clean’ values as strings for the user’s location; i.e. 1,000,000.00 comma separators, float truncation, etc. Available for most of JavaScript’s primitive types (any data you’ll serve into the template).

  • style (str, default None.) – HTML inline style properties like font and colors. Will be applied to a div with the text in it.

  • sticky (bool, default True) – Whether the tooltip should follow the mouse.

  • **kwargs (Assorted.) – These values will map directly to the Leaflet Options. More info available here: https://leafletjs.com/reference-1.6.0#tooltip

Examples

# Provide fields and aliases, with Style. >>> GeoJsonTooltip( >>> fields=[‘CNTY_NM’, ‘census-pop-2015’, ‘census-md-income-2015’], >>> aliases=[‘County’, ‘2015 Census Population’, ‘2015 Median Income’], >>> localize=True, >>> style=(‘background-color: grey; color: white; font-family:’ >>> ‘courier new; font-size: 24px; padding: 10px;’) >>> ) # Provide fields, with labels off and fixed tooltip positions. >>> GeoJsonTooltip(fields=(‘CNTY_NM’,), labels=False, sticky=False)

class folium.features.LatLngPopup

Bases: branca.element.MacroElement

When one clicks on a Map that contains a LatLngPopup, a popup is shown that displays the latitude and longitude of the pointer.

class folium.features.RegularPolygonMarker(location, number_of_sides=4, rotation=0, radius=15, popup=None, tooltip=None, **kwargs)

Bases: folium.elements.JSCSSMixin, folium.map.Marker

Custom markers using the Leaflet Data Vis Framework.

Parameters
  • location (tuple or list) – Latitude and Longitude of Marker (Northing, Easting)

  • number_of_sides (int, default 4) – Number of polygon sides

  • rotation (int, default 0) – Rotation angle in degrees

  • radius (int, default 15) – Marker radius, in pixels

  • popup (string or Popup, optional) – Input text or visualization for object displayed when clicking.

  • tooltip (str or folium.Tooltip, optional) – Display a text when hovering over the object.

  • **kwargs – See vector layers path_options for additional arguments.

  • https (//humangeo.github.io/leaflet-dvf/) –

default_js = [('dvf_js', 'https://cdnjs.cloudflare.com/ajax/libs/leaflet-dvf/0.3.0/leaflet-dvf.markers.min.js')]
class folium.features.TopoJson(data, object_path, style_function=None, name=None, overlay=True, control=True, show=True, smooth_factor=None, tooltip=None)

Bases: folium.elements.JSCSSMixin, folium.map.Layer

Creates a TopoJson object for plotting into a Map.

Parameters
  • data (file, dict or str.) – The TopoJSON data you want to plot. * If file, then data will be read in the file and fully embedded in Leaflet’s JavaScript. * If dict, then data will be converted to JSON and embedded in the JavaScript. * If str, then data will be passed to the JavaScript as-is.

  • object_path (str) – The path of the desired object into the TopoJson structure. Ex: ‘objects.myobject’.

  • style_function (function, default None) – A function mapping a TopoJson geometry to a style dict.

  • name (string, default None) – The name of the Layer, as it will appear in LayerControls

  • overlay (bool, default False) – Adds the layer as an optional overlay (True) or the base layer (False).

  • control (bool, default True) – Whether the Layer will be included in LayerControls.

  • show (bool, default True) – Whether the layer will be shown on opening (only for overlays).

  • smooth_factor (float, default None) – How much to simplify the polyline on each zoom level. More means better performance and smoother look, and less means more accurate representation. Leaflet defaults to 1.0.

  • tooltip (GeoJsonTooltip, Tooltip or str, default None) – Display a text when hovering over the object. Can utilize the data, see folium.GeoJsonTooltip for info on how to do that.

Examples

>>> # Providing file that shall be embeded.
>>> TopoJson(open('foo.json'), 'object.myobject')
>>> # Providing filename that shall not be embeded.
>>> TopoJson('foo.json', 'object.myobject')
>>> # Providing dict.
>>> TopoJson(json.load(open('foo.json')), 'object.myobject')
>>> # Providing string.
>>> TopoJson(open('foo.json').read(), 'object.myobject')
>>> # Provide a style_function that color all states green but Alabama.
>>> style_function = lambda x: {'fillColor': '#0000ff' if
...                             x['properties']['name']=='Alabama' else
...                             '#00ff00'}
>>> TopoJson(topo_json, 'object.myobject', style_function=style_function)
default_js = [('topojson', 'https://cdnjs.cloudflare.com/ajax/libs/topojson/1.6.9/topojson.min.js')]
get_bounds()

Computes the bounds of the object itself (not including it’s children) in the form [[lat_min, lon_min], [lat_max, lon_max]]

render(**kwargs)

Renders the HTML representation of the element.

style_data()

Applies self.style_function to each feature of self.data.

class folium.features.Vega(data, width=None, height=None, left='0%', top='0%', position='relative')

Bases: folium.elements.JSCSSMixin, branca.element.Element

Creates a Vega chart element.

Parameters
  • data (JSON-like str or object) – The Vega description of the chart. It can also be any object that has a method to_json, so that you can (for instance) provide a vincent chart.

  • width (int or str, default None) – The width of the output element. If None, either data[‘width’] (if available) or ‘100%’ will be used. Ex: 120, ‘120px’, ‘80%’

  • height (int or str, default None) – The height of the output element. If None, either data[‘width’] (if available) or ‘100%’ will be used. Ex: 120, ‘120px’, ‘80%’

  • left (int or str, default '0%') – The horizontal distance of the output with respect to the parent HTML object. Ex: 120, ‘120px’, ‘80%’

  • top (int or str, default '0%') – The vertical distance of the output with respect to the parent HTML object. Ex: 120, ‘120px’, ‘80%’

  • position (str, default 'relative') – The position argument that the CSS shall contain. Ex: ‘relative’, ‘absolute’

default_js = [('d3', 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js'), ('vega', 'https://cdnjs.cloudflare.com/ajax/libs/vega/1.4.3/vega.min.js'), ('jquery', 'https://code.jquery.com/jquery-2.1.0.min.js')]
render(**kwargs)

Renders the HTML representation of the element.

class folium.features.VegaLite(data, width=None, height=None, left='0%', top='0%', position='relative')

Bases: branca.element.Element

Creates a Vega-Lite chart element.

Parameters
  • data (JSON-like str or object) – The Vega-Lite description of the chart. It can also be any object that has a method to_json, so that you can (for instance) provide an Altair chart.

  • width (int or str, default None) – The width of the output element. If None, either data[‘width’] (if available) or ‘100%’ will be used. Ex: 120, ‘120px’, ‘80%’

  • height (int or str, default None) – The height of the output element. If None, either data[‘width’] (if available) or ‘100%’ will be used. Ex: 120, ‘120px’, ‘80%’

  • left (int or str, default '0%') – The horizontal distance of the output with respect to the parent HTML object. Ex: 120, ‘120px’, ‘80%’

  • top (int or str, default '0%') – The vertical distance of the output with respect to the parent HTML object. Ex: 120, ‘120px’, ‘80%’

  • position (str, default 'relative') – The position argument that the CSS shall contain. Ex: ‘relative’, ‘absolute’

render(**kwargs)

Renders the HTML representation of the element.