Search code examples
pythonpyqt5folium

How do I create a popup on folium map using data from json file?


How do I go about creating a popup on my folium map to show information about the nodes ? As show below, my folium map is currently drawing the data from a json file that I have downloaded from overpass turbo. Hence the blue outline of the buildings on the map. I am having trouble to create a popup such that when a user click on the building, a popup would appear to display information, like in overpass turbo. Currently, I am trying to retrieve all the information under "properties", but my codes does nothing, as when I tried to click on the building, instead of a popup, click on the map will just zoom in instead.

*PS my current GUI is based on a answer provided to me on another question I have posted "How to include folium map into PyQt5 application window?"

Folium Map

enter image description here

CODE

 with open('exportBuildings.geojson') as access_json:
            read_content = json.load(access_json)

 feature_access = read_content['features']


# Creating folium map
for feature_data in feature_access:
            buildingName = feature_data['properties']

m = folium.Map(location=[1.400150, 103.910172], titles="Punggol", zoom_start=17)
nodeData = os.path.join('exportFULL.geojson')
folium.GeoJson(nodeData).add_child(folium.Popup(buildingName))
folium.GeoJson(nodeData).add_to(m)
data = io.BytesIO()
m.save(data, close_file=False)
self.view.setHtml(data.getvalue().decode())

JSON FORMAT

"type": "Feature",
  "properties": {
    "@id": "way/768461439",
    "building": "train_station",
    "layer": "1",
    "name": "Damai LRT",
    "wikidata": "Q7313275",
    "wikipedia": "en:Damai LRT station"
  },

Solution

  • Explanation:

    The problem is that you are creating 2 GeoJSON items:

    folium.GeoJson(nodeData).add_child(folium.Popup(buildingName))
    folium.GeoJson(nodeData).add_to(m)

    In the first one you add popup as a child but you do not add it to the map, in the second you add it to the map but it does not have popup, that is, only a GeoJson will be seen on the map without popup.

    Solution:

    The solution is to create only a GeoJson where the item is added and the popup is established as a child:

    geo_json = folium.GeoJson(nodeData)
    geo_json.add_child(folium.Popup(buildingName))
    geo_json.add_to(m)
    

    that taking advantage of the add_to() and add_child() property that returns the same item can be reduced to:

    folium.GeoJson(nodeData).add_to(m).add_child(folium.Popup(buildingName))
    

    Or

    folium.GeoJson(nodeData).add_child(folium.Popup(buildingName)).add_to(m)