Search code examples
pythonleafletpopupgeojsonfolium

How to add unique popups to each GeoJSON polygon in Folium using Python


I am trying to create a Folium map with buildings. I want to add a popup to each building based on its corresponding openbare_ruimte property. However, the code that I wrote adds the same popup to all buildings.

I have consulted several threads on this issue (#1023, #1060, #popups, #popups2), but have been unable to get it to work.

Does anyone know how I can add each buildings' openbare_ruimte property to its popup?

import json
import requests
import folium

url = "http://geodata.nationaalgeoregister.nl/bag/wfs?service=wfs&version=2.0.0&request=GetFeature&outputFormat=json&count=25&srsName=epsg:4326&typeName=bag:verblijfsobject&cql_filter=%28bag:woonplaats=%27Groningen%27%29"
js_data = json.loads(requests.get(url).text)


m = folium.Map(location=[53.2193835, 6.5665018], zoom_start=13)

fg = folium.map.FeatureGroup(name='Buildings').add_to(m)

#Add the polygons features to the FeatureGroup layer
for feature in js_data['features']:
    fg.add_child(folium.GeoJson(feature['properties']['pandgeometrie']))

#Add popups to the FeatureGroup layer
for feature in js_data['features']:
    fg.add_child(folium.Popup(feature['properties']['openbare_ruimte']))


folium.LayerControl().add_to(m)

m

Solution

  • If I understand correctly, you want each building to provide a popup showing its address (street I suppose).

    This code seems to do what you desire:

    import json
    import requests
    import folium
    
    url = "http://geodata.nationaalgeoregister.nl/bag/wfs?service=wfs&version=2.0.0&request=GetFeature&outputFormat=json&count=25&srsName=epsg:4326&typeName=bag:verblijfsobject&cql_filter=%28bag:woonplaats=%27Groningen%27%29"
    js_data = json.loads(requests.get(url).text)
    
    
    m = folium.Map(location=[53.2193835, 6.5665018], zoom_start=13)
    
    fg = folium.map.FeatureGroup(name='Buildings').add_to(m)
    
    for feature in js_data['features']:
        b = folium.GeoJson(feature['properties']['pandgeometrie'])
        b.add_child(folium.Popup(feature['properties']['openbare_ruimte']))
        fg.add_child(b)
    
    
    folium.LayerControl().add_to(m)
    
    m
    

    and you get, as an example:

    enter image description here