Search code examples
pythongismodelingfolium

How to print index of for loop in FOLIUM MAP (Python)?


I am writing the following Python code to print numbers beside Folium ICON. I need these indices to be dynamic, meaning, I have a for loop, I want index value to be printed in the HTML line of the code.

for point in range(0, len(coordinates_st)):
    # showing number
    folium.Marker(location=[72.89, -124.59+2], icon=DivIcon(
        icon_size=(150, 36),
        icon_anchor=(7, 20),
        html='<div style="font-size: 18pt;">r{point}</div>',
    )).add_to(map_st)

I want to print number beside the HOME in the image below (loop indexing from for loop, not fixed 1, 2 as currently written in the code).

    for point in range(0, len(coordinates_st)):
        # showing number
        folium.Marker(location=[72.89, -124.59+2], icon=DivIcon(
            icon_size=(150, 36),
            icon_anchor=(7, 20),
            html='<div style="font-size: 18pt;">1, 2</div>',
        )).add_to(map_st)

Current folium map


Solution

  • In this case, the index can be displayed using f-string notation. Since the data is not presented, we can use geopandas data to display the usual markers for the cities of the world, with the index next to them. characters.

    import folium
    import geopandas as gpd
    
    geo_df = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))
    
    map_st = folium.Map(location=[50.08528, 14.46403], tiles="OpenStreetMap", zoom_start=4)
    
    for i,row in geo_df.iterrows():
        folium.Marker(location=[row.geometry.y, row.geometry.x+2],
                      icon=folium.DivIcon(
                          icon_size=(150, 36),
                          icon_anchor=(7, 20),
                          html=f'<div style="font-size: 12pt;">{i}</div>',
        )).add_to(map_st)
        folium.Marker(location=[row.geometry.y, row.geometry.x],icon=folium.Icon(color="black", icon="home"),
    ).add_to(map_st)
    map_st
    

    enter image description here