Skip to content

Folium Utils

background_color

Background color of a folium map.

set_background_color_of_map

set_background_color_of_map(folium_map: Map, color: str) -> Map

Set the background color of the map, visible where no tile or feature covers it.

Parameters:

Name Type Description Default
folium_map Map

The map. The function adds a style element to its header.

required
color str

A CSS color, for example '#ffffff' or 'white'.

required

Returns:

Type Description
Map

The same map.

Source code in src/mesqual/utils/folium_utils/background_color.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def set_background_color_of_map(folium_map: folium.Map, color: str) -> folium.Map:
    """Set the background color of the map, visible where no tile or feature covers it.

    Args:
        folium_map: The map. The function adds a style element to its header.
        color: A CSS color, for example `'#ffffff'` or `'white'`.

    Returns:
        The same map.
    """
    css = f"""
    <style>
        .leaflet-container {{
            background-color: {color} !important;
        }}
    </style>
    """
    folium_map.get_root().header.add_child(folium.Element(css))
    return folium_map

country_plotter

Country shapes on folium maps.

MapCountryPlotter

Draws country shapes on folium maps, for example as a background for a map of results.

A country id is compared exactly, case included, with the values of the columns in GEOJSON_ID_COLUMNS, in this order. The rows of the first column with a match are the country. So an id finds a country only if the file has it in one of these columns. In the Natural Earth file some countries have -99 as ISO code: 'FRA' finds nothing, 'FR' finds France through FIPS_10_. The id 'NO' is looked up as 'NOR', the sovereign code of Norway.

Parameters:

Name Type Description Default
geojson_file_path str

GeoJSON file with the country shapes, coordinates in longitude and latitude (EPSG:4326). The CRS of the file is overwritten with EPSG:4326, not converted. Default: the Natural Earth countries that ship with mesqual.

None
Source code in src/mesqual/utils/folium_utils/country_plotter.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
class MapCountryPlotter:
    """Draws country shapes on folium maps, for example as a background for a map of results.

    A country id is compared exactly, case included, with the values of the
    columns in `GEOJSON_ID_COLUMNS`, in this order. The rows of the first
    column with a match are the country. So an id finds a country only if the
    file has it in one of these columns. In the Natural Earth file some
    countries have `-99` as ISO code: `'FRA'` finds nothing, `'FR'` finds
    France through `FIPS_10_`. The id `'NO'` is looked up as `'NOR'`, the
    sovereign code of Norway.

    Args:
        geojson_file_path: GeoJSON file with the country shapes, coordinates
            in longitude and latitude (EPSG:4326). The CRS of the file is
            overwritten with EPSG:4326, not converted. Default: the Natural
            Earth countries that ship with mesqual.
    """

    GEOJSON_ID_COLUMNS = ['ISO_A2', 'ISO_A3', 'SOV_A3', 'FIPS_10_']
    DEFAULT_STYLE = {'fillColor': '#C2C2C2', 'color': 'white', 'weight': 0.5, 'fillOpacity': 1}
    _AUTO_REPLACEMENTS = {
        'NO': 'NOR',
    }

    def __init__(self, geojson_file_path: str = None):
        if geojson_file_path is None:
            gdf = _load_countries_geojson()
        else:
            gdf = gpd.read_file(geojson_file_path)
        gdf.loc[:, 'geometry'] = gdf.buffer(0)
        gdf.set_crs('EPSG:4326', allow_override=True, inplace=True)
        self._countries_gdf = gdf

    def add_countries_to_feature_group(
        self, fg: folium.FeatureGroup, countries: list[str], style: dict = None
    ) -> folium.FeatureGroup:
        """Add the shapes of the given countries to the feature group, as one `folium.GeoJson`.

        An id without match is skipped. If no id matches, nothing is added.

        Args:
            fg: The feature group.
            countries: Country ids, looked up as described in the class docstring.
            style: Style keys that replace those of `DEFAULT_STYLE`.

        Returns:
            The same feature group.
        """
        countries_gdf = self._find_countries(countries)
        if countries_gdf.empty:
            return fg

        style_dict = self._get_updated_style_dict(style)
        folium.GeoJson(countries_gdf, style_function=lambda x: style_dict).add_to(fg)
        return fg

    def _get_updated_style_dict(self, style: dict = None) -> dict:
        style_dict = self.DEFAULT_STYLE.copy()
        if style:
            style_dict.update(style)
        return style_dict

    def add_all_countries_except(
        self, fg: folium.FeatureGroup, excluded_countries: list[str], style: dict = None
    ) -> folium.FeatureGroup:
        """Add the shapes of all countries of the file except the given ones, as one `folium.GeoJson`.

        Args:
            fg: The feature group.
            excluded_countries: Ids of the countries to leave out. An id without match is skipped.
            style: Style keys that replace those of `DEFAULT_STYLE`.

        Returns:
            The same feature group.
        """
        excluded_gdf = self._find_countries(excluded_countries)
        all_countries = self._countries_gdf.copy()

        if not excluded_gdf.empty:
            all_countries = all_countries[~all_countries.index.isin(excluded_gdf.index)]

        style_dict = self._get_updated_style_dict(style)
        folium.GeoJson(all_countries, style_function=lambda x: style_dict).add_to(fg)
        return fg

    def get_geojson_for_country(self, country_id: str) -> gpd.GeoDataFrame:
        """Return the rows of the file that match a country id, as a `GeoDataFrame`.

        Args:
            country_id: The id, looked up as described in the class docstring.

        Returns:
            The matching rows of the first id column with a match, an empty
                `GeoDataFrame` if no column matches.
        """
        _country_id = self._AUTO_REPLACEMENTS.get(country_id, country_id)

        for column in self.GEOJSON_ID_COLUMNS:
            if column not in self._countries_gdf.columns:
                continue
            match = self._countries_gdf[self._countries_gdf[column] == _country_id]
            if not match.empty:
                return match
        return gpd.GeoDataFrame()

    def _find_countries(self, countries: list[str]) -> gpd.GeoDataFrame:
        matches = gpd.GeoDataFrame()
        for country in countries:
            country_match = self.get_geojson_for_country(country)
            if not country_match.empty:
                matches = pd.concat([matches, country_match])
        return matches

add_countries_to_feature_group

add_countries_to_feature_group(fg: FeatureGroup, countries: list[str], style: dict = None) -> FeatureGroup

Add the shapes of the given countries to the feature group, as one folium.GeoJson.

An id without match is skipped. If no id matches, nothing is added.

Parameters:

Name Type Description Default
fg FeatureGroup

The feature group.

required
countries list[str]

Country ids, looked up as described in the class docstring.

required
style dict

Style keys that replace those of DEFAULT_STYLE.

None

Returns:

Type Description
FeatureGroup

The same feature group.

Source code in src/mesqual/utils/folium_utils/country_plotter.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def add_countries_to_feature_group(
    self, fg: folium.FeatureGroup, countries: list[str], style: dict = None
) -> folium.FeatureGroup:
    """Add the shapes of the given countries to the feature group, as one `folium.GeoJson`.

    An id without match is skipped. If no id matches, nothing is added.

    Args:
        fg: The feature group.
        countries: Country ids, looked up as described in the class docstring.
        style: Style keys that replace those of `DEFAULT_STYLE`.

    Returns:
        The same feature group.
    """
    countries_gdf = self._find_countries(countries)
    if countries_gdf.empty:
        return fg

    style_dict = self._get_updated_style_dict(style)
    folium.GeoJson(countries_gdf, style_function=lambda x: style_dict).add_to(fg)
    return fg

add_all_countries_except

add_all_countries_except(fg: FeatureGroup, excluded_countries: list[str], style: dict = None) -> FeatureGroup

Add the shapes of all countries of the file except the given ones, as one folium.GeoJson.

Parameters:

Name Type Description Default
fg FeatureGroup

The feature group.

required
excluded_countries list[str]

Ids of the countries to leave out. An id without match is skipped.

required
style dict

Style keys that replace those of DEFAULT_STYLE.

None

Returns:

Type Description
FeatureGroup

The same feature group.

Source code in src/mesqual/utils/folium_utils/country_plotter.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def add_all_countries_except(
    self, fg: folium.FeatureGroup, excluded_countries: list[str], style: dict = None
) -> folium.FeatureGroup:
    """Add the shapes of all countries of the file except the given ones, as one `folium.GeoJson`.

    Args:
        fg: The feature group.
        excluded_countries: Ids of the countries to leave out. An id without match is skipped.
        style: Style keys that replace those of `DEFAULT_STYLE`.

    Returns:
        The same feature group.
    """
    excluded_gdf = self._find_countries(excluded_countries)
    all_countries = self._countries_gdf.copy()

    if not excluded_gdf.empty:
        all_countries = all_countries[~all_countries.index.isin(excluded_gdf.index)]

    style_dict = self._get_updated_style_dict(style)
    folium.GeoJson(all_countries, style_function=lambda x: style_dict).add_to(fg)
    return fg

get_geojson_for_country

get_geojson_for_country(country_id: str) -> GeoDataFrame

Return the rows of the file that match a country id, as a GeoDataFrame.

Parameters:

Name Type Description Default
country_id str

The id, looked up as described in the class docstring.

required

Returns:

Type Description
GeoDataFrame

The matching rows of the first id column with a match, an empty GeoDataFrame if no column matches.

Source code in src/mesqual/utils/folium_utils/country_plotter.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def get_geojson_for_country(self, country_id: str) -> gpd.GeoDataFrame:
    """Return the rows of the file that match a country id, as a `GeoDataFrame`.

    Args:
        country_id: The id, looked up as described in the class docstring.

    Returns:
        The matching rows of the first id column with a match, an empty
            `GeoDataFrame` if no column matches.
    """
    _country_id = self._AUTO_REPLACEMENTS.get(country_id, country_id)

    for column in self.GEOJSON_ID_COLUMNS:
        if column not in self._countries_gdf.columns:
            continue
        match = self._countries_gdf[self._countries_gdf[column] == _country_id]
        if not match.empty:
            return match
    return gpd.GeoDataFrame()

lat_lon_popup

Popup with the coordinates of a click on a folium map.

CustomLatLngPopup

Bases: LatLngPopup

Popup that shows the latitude and longitude of the point that you click on the map.

The popup also shows the point as WKT text, for example POINT(9.1234 48.5678), to copy it into a geometry.

Examples:

>>> import folium
>>> folium_map = folium.Map()
>>> folium_map = folium_map.add_child(CustomLatLngPopup())
>>> '"<br><br>POINT("' in folium_map.get_root().render()
True
Source code in src/mesqual/utils/folium_utils/lat_lon_popup.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class CustomLatLngPopup(folium.LatLngPopup):
    """Popup that shows the latitude and longitude of the point that you click on the map.

    The popup also shows the point as WKT text, for example `POINT(9.1234 48.5678)`,
    to copy it into a geometry.

    Examples:
        >>> import folium
        >>> folium_map = folium.Map()
        >>> folium_map = folium_map.add_child(CustomLatLngPopup())
        >>> '"<br><br>POINT("' in folium_map.get_root().render()
        True
    """

    _template = folium.features.Template("""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.popup();
            function latLngPop(e) {
                {{this.get_name()}}
                    .setLatLng(e.latlng)
                    .setContent("Latitude: " + e.latlng.lat.toFixed(4) +
                                "<br>Longitude: " + e.latlng.lng.toFixed(4) +
                                "<br><br>POINT("+e.latlng.lng.toFixed(4)+" "+e.latlng.lat.toFixed(4)+")")
                    .openOn({{this._parent.get_name()}});
                }
            {{this._parent.get_name()}}.on('click', latLngPop);
        {% endmacro %}
    """)