Skip to content

Map of observations

This module provides rendering of observations on an interactive map, with a variety of tilesets available.

Note: OSM, ESRI, and CartoDB map tiles are served without authentication/tokens, and so render correctly on the huggingface deployment. The Stamen tiles render on localhost but require a token to present on a 3rd-party site.

create_map(tile_name, location, zoom_start=7)

Create a folium map with the specified tile layer

Parameters:

Name Type Description Default
tile_name str

The name of the tile layer to use. Options include: 'Open Street Map', 'Esri Ocean', 'Esri Images', 'Stamen Toner', 'Stamen Watercolor', 'CartoDB Positron', 'CartoDB Dark_Matter'.

required
location Tuple

Coordinates (lat, lon) of the map center, as floats.

required
zoom_start int

The initial zoom level for the map. Default is 7.

7

Returns:

Type Description
Map

folium.Map: A folium Map object with the specified settings.

Source code in src/obs_map.py
 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
def create_map(tile_name:str, location:Tuple[float], zoom_start: int = 7) -> folium.Map:
    """
    Create a folium map with the specified tile layer

    Parameters:
        tile_name (str): The name of the tile layer to use. Options include:
                        'Open Street Map', 'Esri Ocean', 'Esri Images', 
                        'Stamen Toner', 'Stamen Watercolor', 
                        'CartoDB Positron', 'CartoDB Dark_Matter'.
        location (Tuple): Coordinates (lat, lon) of the map center, as floats.
        zoom_start (int, optional): The initial zoom level for the map. Default is 7.

    Returns:
        folium.Map: A folium Map object with the specified settings.
    """
    # https://xyzservices.readthedocs.io/en/stable/gallery.html 
    # get teh attribtuions from here once we pick the 2-3-4 options 
    # make esri ocean the default
    m = folium.Map(location=location, zoom_start=zoom_start,
                   tiles='Esri.OceanBasemap', attr="Esri")
    #m = folium.Map(location=location, zoom_start=zoom_start)

    attr = ""
    if tile_name == 'Open Street Map':
        folium.TileLayer('openstreetmap').add_to(m)
        pass

    #Esri.OceanBasemap
    elif tile_name == 'Esri Ocean':
        pass # made this one default ()
        #attr = "Esri"
        #folium.TileLayer('Esri.OceanBasemap', attr=attr).add_to(m)

    elif tile_name == 'Esri Images':
        attr = "Esri — Source: Esri, i-cubed, USDA"
        #folium.TileLayer('stamenterrain', attr=attr).add_to(m)
        folium.TileLayer('Esri.WorldImagery', attr=attr).add_to(m)
    elif tile_name == 'Stamen Toner':
        attr = "Stamen"
        folium.TileLayer('stamentoner', attr=attr).add_to(m)
    elif tile_name == 'Stamen Watercolor':
        attr = "Stamen"
        folium.TileLayer('Stadia.StamenWatercolor', attr=attr).add_to(m)
    elif tile_name == 'CartoDB Positron':
        folium.TileLayer('cartodb positron').add_to(m)
    elif tile_name == 'CartoDB Dark_Matter':
        folium.TileLayer('cartodb dark_matter').add_to(m)

    #folium.LayerControl().add_to(m)
    return m

present_obs_map(dataset_id='Saving-Willy/Happywhale-kaggle', data_files='data/train-00000-of-00001.parquet', dbg_show_extra=False)

Render map plus tile selector, with markers for whale observations

This function loads whale observation data from a specified dataset and file, creates a pandas DataFrame compliant with Folium/Streamlit maps, and renders an interactive map with markers for each observation. The map allows users to select a tileset, and displays markers with species-specific colors.

Parameters:

Name Type Description Default
dataset_id str

The ID of the dataset to load from Hugging Face. Default is "Saving-Willy/Happywhale-kaggle".

'Saving-Willy/Happywhale-kaggle'
data_files str

The path to the data file to load. Default is "data/train-00000-of-00001.parquet".

'data/train-00000-of-00001.parquet'
dbg_show_extra bool

If True, add a few extra sample markers for visualization. Default is False.

False

Returns:

Name Type Description
dict dict

Selected data from the Folium/leaflet.js interactions in the browser.

Source code in src/obs_map.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def present_obs_map(dataset_id:str = "Saving-Willy/Happywhale-kaggle",
                    data_files:str = "data/train-00000-of-00001.parquet", 
                    dbg_show_extra:bool = False) -> dict:
    """
    Render map plus tile selector, with markers for whale observations


    This function loads whale observation data from a specified dataset and
    file, creates a pandas DataFrame compliant with Folium/Streamlit maps, and
    renders an interactive map with markers for each observation.  The map
    allows users to select a tileset, and displays markers with species-specific
    colors.

    Args:
        dataset_id (str): The ID of the dataset to load from Hugging Face. Default is "Saving-Willy/Happywhale-kaggle".
        data_files (str): The path to the data file to load. Default is "data/train-00000-of-00001.parquet".
        dbg_show_extra (bool): If True, add a few extra sample markers for visualization. Default is False.

    Returns:
        dict: Selected data from the Folium/leaflet.js interactions in the browser.

    """

    # load/download data from huggingface dataset
    metadata = load_dataset(dataset_id, data_files=data_files)

    # make a pandas df that is compliant with folium/streamlit maps
    _df = pd.DataFrame({
        'lat': metadata["train"]["latitude"],
        'lon': metadata["train"]["longitude"],
        'species': metadata["train"]["predicted_class"],}
    )
    if dbg_show_extra:
        # add a few samples to visualise colours 
        _df.loc[len(_df)] = {'lat': 0, 'lon': 0, 'species': 'rough_toothed_dolphin'}
        _df.loc[len(_df)] = {'lat': -3, 'lon': 0, 'species': 'pygmy_killer_whale'}
        _df.loc[len(_df)] = {'lat': 45.7, 'lon': -2.6, 'species': 'humpback_whale'}

    ocean_loc = 0, 10
    selected_tile = st.selectbox("Choose a tile set", tile_sets, index=None, placeholder="Choose a tile set...", disabled=False)
    map_ = create_map(selected_tile, ocean_loc, zoom_start=2)

    folium.Marker(
        location=ocean_loc,
        popup="Atlantis",
        tooltip="Atlantis",
        icon=folium.Icon(color='blue', icon='info-sign')
    ).add_to(map_)

    for _, row in _df.iterrows():
        c = whale2color.get(row['species'], 'red')
        msg = f"[D] color for {row['species']} is {c}"
        m_logger.debug(msg) # depends on m_logger logging level (*not* the main st app's logger)
        #m_logger.info(msg)

        kw = {"prefix": "fa", "color": 'gray', "icon_color": c, "icon": "binoculars" } 
        folium.Marker(
            location=[row['lat'], row['lon']],
            popup=f"{row['species']} ",
            tooltip=row['species'],
            icon=folium.Icon(**kw)
        ).add_to(map_)
        #st.info(f"Added marker for {row['name']} {row['lat']} {row['lon']}")

    st_data = st_folium(map_, width=725)

    # workaround for correctly showing js components in tabs
    js_show_zeroheight_iframe(
        component_iframe_title="streamlit_folium.st_folium",
        height=800,
    )
    # this is just debug info -- 
    #st.info("[D]" + str(metadata.column_names))

    return st_data