Skip to content

Folium Geojson: how to apply the stylefunction within a loop #1608

Closed

Description

@MendesJ2

I'm trying to colorize each region on the map based on the residence of each user. For instance, if the user lives in Porto, the regions Braga and Aveiro should be red. On the other case, if the user lives in Lisbon, Setúbal must be red.

Each user is in a feature group.

I would like to keep iterating the dataframe

Here is a simple sample of the script:

import folium
import json
import pandas as pd

path = r'file.geojson'
with open(path) as file:
    data = json.load(file)

list_users = [
    [1,'Lisboa'],
    [2,'Porto'],
    [3,'Porto']
]
df_users = pd.DataFrame(list_users,columns = ['ID','Place'])


my_map = folium.Map(location=[39, -5],
        zoom_start=7, min_zoom=4, max_zoom=15,
        max_bounds=True,
        tiles="cartodbpositron"
        )

d = {} # dict to save the feature groups

for _,user in df_users.iterrows():


    fg_name = "FG_{0}".format(user.ID)
    d[fg_name] = folium.FeatureGroup(name=user.ID,overlay=True,show=False)
    fg_value = d[fg_name]


    if user.Place == 'Lisboa':
        list_red_places = ['Setúbal']
    elif user.Place == 'Porto':
        list_red_places = ['Braga','Aveiro']


    folium.GeoJson(data=data,
                style_function=lambda x: {'fillColor': 'red' if x['properties']['Distrito'] in list_red_places else 'green',
                            'fillOpacity': .5 if x['properties']['Distrito'] in list_red_places else 0.1,
                            'weight': 0.1    
                        }).add_to(fg_value) 


    fg_value.add_to(my_map)
folium.LayerControl().add_to(my_map)
my_map

All the features have the same red and green regions. I believe that the issue is in the stylefuncion since that the lambda function retrieves only the last iteration.

All the 3 users have the same red regions. the 1st user should have a different one.

Here's the map for the 3 users:

user_3

user_2

user_1

Activity

  1. Conengmo commented on Nov 17, 2022

    @Conengmo
    Member

    I don't see an issue with your code at first glance. I'm afraid we don't have the capacity to help you further, so I'll close this issue. You might get more help on Stackoverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions