Python Folium – How to Add Marker in Random Place Using Leaflet and JavaScript

foliumjavascriptleafletpython

I would like to add a marker in a random place in Python folium.

I found the example, which I would like to implement, which is here:

http://kody.wig.pl/javascript/dodawanie-przesuwanie-i-kasowanie-markerow-leaflet/

but when I started to make it in Python folium, where my code look like this:

 mapJsVar = map.get_name()

 map.get_root().html.add_child(folium.Element("""

 <div class="marker-position">Click on the map and play with the marker</div>


 <script type="text/javascript">
 {map}.on('click',addMarker);
 </script>
 """.replace("{map}", mapJsVar)))

I have an error in my JavaScript console:

   **Uncaught ReferenceError: map_b6651fe88e04a627a682cee4dbed8fa4 is not defined**

I don't know why does it still appear, as I clearly declared the replacement. Any ideas?

Best Answer

Folium injects the JS code to a place before the line where map object is created.

enter image description here

In the image, Line 1 is where folium adds the code. Line 2 is where the map object is created. Line 1 always run before Line 2. map object is called before defined, so you get the error.

Therefore, wrap the script to be injected always in $(document).ready(function(){ __SCRIPT_HERE__ });. This function ensures that the injected code is run after the map object is created.

Script:

import folium

m = folium.Map()

mapJsVar = m.get_name()

m.get_root().html.add_child(folium.Element("""
<script type="text/javascript">

$(document).ready(function () {
  {map}.on("click", addMarker);

  function addMarker(e) {
    // ustawiamy aby marker był przesuwalny
    const marker = new L.marker(e.latlng, {
      draggable: true,
    }).addTo({map});
  }
});

</script>
""".replace("{map}", mapJsVar)))

m

Demo:

enter image description here