Add a Clickevent Function to multiple Folium Markers with Python

Question:

I have an html file that has been generated with folium, within are multiple folium markers representing a range of different locations.

With python I want to go through the html file and add a click event function to each marker so that on the event the lat/lon will be returned.

I already have the function created:

.on('click', function(e) {
     var point = e.latlng;

     document.querySelector('meta[name="point"]').setAttribute("content", point);
})

And here is an example of the section of folium marker where I need to append the function (after ‘addTo(map)’):

var marker_b05545cf05b08cd5d04cd4ea09541226 = L.marker(
     [51.7678, -0.00675564],
     {}
     ).addTo(map_97dd2eeb89fe7d0a2f70926e61b8eeab);

So hopefully the final code should look like this:

var marker_b05545cf05b08cd5d04cd4ea09541226 = L.marker(
     [51.7678, -0.00675564],
     {}
     ).addTo(map_97dd2eeb89fe7d0a2f70926e61b8eeab).on('click', function(e) {
          var point = e.latlng;

          document.querySelector('meta[name="point"]').setAttribute("content", point);
});

I’ve tried to see if I could do this with Beautiful Soup but couldn’t find anything as that normally revolves around editing specific tags with ids etc, and have also briefly looked into jinja2 but it doesn’t seem like you can append to specific parts of the html script, rather just at the end of it.

Any help or advice on where to look would be greatly appreciated.

Asked By: wbleakley

||

Answers:

You can modify the Marker template, to include the onClick event (javascript component).
The following example will alert latlng on click.

import folium
from jinja2 import Template
from folium.map import Marker

# Modify Marker template to include the onClick event
click_template = """{% macro script(this, kwargs) %}
    var {{ this.get_name() }} = L.marker(
        {{ this.location|tojson }},
        {{ this.options|tojson }}
    ).addTo({{ this._parent.get_name() }}).on('click', onClick);
{% endmacro %}"""

# Change template to custom template
Marker._template = Template(click_template)

location_center = [51.7678, -0.00675564]
m = folium.Map(location_center, zoom_start=13)

# Create the onClick listener function as a branca element and add to the map html
click_js = """function onClick(e) {
                 var point = e.latlng; alert(point)
                 }"""
                 
e = folium.Element(click_js)
html = m.get_root()
html.script.get_root().render()
html.script._children[e.get_name()] = e

#Add marker (click on map an alert will display with latlng values)
marker = folium.Marker([51.7678, -0.00675564]).add_to(m)
Answered By: PeaceLeka
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.