5

I was wondering if there is a way in Folium to get the information on an entity we click on with Folium?

I'd like the map to either open a tab with the attribute information or just send back information on the entity selected without necessarily using a popup.

4 Answers 4

3

You can use GeoJsonTooltip to show selected fields from a GeoDataFrame.

usmap = folium.Map(
    location=[40,-95],
    tiles='cartodbpositron',
    zoom_start=5,
    control_scale=True
)

folium.GeoJson(
    states[['STATE_NAME', 'geometry']].to_json(),
    name='States',
    show=True,
    style_function=lambda x: {
        'fillColor': 'lightblue',
        'color': 'black',
        'weight': 1,
        'fillOpacity':0.7
    },
    highlight_function=lambda x: {
        'fillOpacity':1
    },
    tooltip=folium.features.GeoJsonTooltip(
        fields=['STATE_NAME'],
        aliases=['State name:'],
    ),
).add_to(usmap)
1
  • Thank you for your answer, indeed i do use GeoJsonTooltip for looking at specific informations but what if I'd like to export the information of a specific area when clicking on an entity ?
    – Brocolus
    Feb 24, 2019 at 18:13
3

Actually I have found a great way to do it.. Folium has a feature named LatLngPopUp which creates a popup where you click on the map with its location. I've edited that popup and added a href link which allows the client to click on, and the info tells the server to create a checkpoint and transfers the coordinats to the server. there you go:

class LatLngPopup(MacroElement):
    """
    When one clicks on a Map that contains a LatLngPopup,
    a popup is shown that displays the latitude and longitude of the pointer.

    """
    _template = Template(u"""
            {% macro script(this, kwargs) %}
                var {{this.get_name()}} = L.popup();
                function latLngPop(e) {
                data = e.latlng.lat.toFixed(4) + "," + e.latlng.lng.toFixed(4);
                    {{this.get_name()}}
                        .setLatLng(e.latlng)
                        .setContent( "<br /><a href="+data+"> click </a>")
                        .openOn({{this._parent.get_name()}})
                    }
                {{this._parent.get_name()}}.on('click', latLngPop);

            {% endmacro %}
            """)  # noqa

    def __init__(self):
        super(LatLngPopup, self).__init__()
        self._name = 'LatLngPopup'
2
  • 1
    This works fine. I get the information back to Python by pasting it to a form like document.getElementById("latitude").value = e.latlng.lat.toFixed(4);
    – Joe
    Aug 2, 2020 at 13:54
  • If the map is embedded using an iframe you can pass the values to the outer parent using parent.document.getElementById("longitude").value = e.latlng.lng.toFixed(4);
    – Joe
    Aug 3, 2020 at 13:33
2

There seems to not be support for this in Folium as yet. Quoting from the issue regarding dynamically change/update markers:

"It's import(ant) to understand that folium generates the html with Leaflet javascript. So anything that happens on the map after generation is outside of folium's scope"

See here for more detail

1
  • Since posting this I found a work-around here (the work-around code is in the comment by @davidolmo on Feb 12). But also, there's a pull request that would seemingly resolve this, and it's under review at present here Apr 10, 2019 at 5:38
2

In my case I use folium plugin "Draw" for set markers and framework PyQt5. Everything work fine.

from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
from folium.plugins import Draw
import folium, io, sys, json

if __name__ == '__main__': 
    app = QtWidgets.QApplication(sys.argv)

    m = folium.Map(location=[55.8527, 37.5689], zoom_start=13)

    draw = Draw(
       draw_options={
          'polyline':False,
          'rectangle':True,
          'polygon':True,
          'circle':False,
          'marker':True,
          'circlemarker':False},
       edit_options={'edit':False})
    m.add_child(draw)

    data = io.BytesIO()
    m.save(data, close_file=False)

        

    class WebEnginePage(QtWebEngineWidgets.QWebEnginePage):
       def javaScriptConsoleMessage(self, level, msg, line, sourceID):
          coords_dict = json.loads(msg)
          coords = coords_dict['geometry']['coordinates'][0]
          print(coords)

  view = QtWebEngineWidgets.QWebEngineView()
  page = WebEnginePage(view)
  view.setPage(page)
  view.setHtml(data.getvalue().decode())
  view.show()
  sys.exit(app.exec_())
2
  • For disable alarm you need edit folium lib (../../foluim/plugins/draw,py) line 63 - alert(coords); Oct 28, 2020 at 9:50
  • 3
    This does not answer the question.
    – TomazicM
    Oct 28, 2020 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.