2

I would like to inject Leaflet plugin into Python folium map.

After applying the following code:

map.get_root().header.add_child(folium.CssLink("https://pasichnykvasyl.github.io/Leaflet.BigImage/src/Leaflet.BigImage.css"))
map.get_root().html.add_child(folium.JavascriptLink("https://pasichnykvasyl.github.io/Leaflet.BigImage/src/Leaflet.BigImage.js"))

png_js = '''
L.control.bigImage({position: 'topleft'}).addTo{map};
'''.replace("{map}", mapJsVar)

map.get_root().script.add_child(Element(png_js))

I can't see the plugin anywhere on my map. Despite the demo version, which programmatically looks exactly the same https://pasichnykvasyl.github.io/Leaflet.BigImage/

My console says nothing.

Where did I make mistake then?

1 Answer 1

5

In png_js , change .addTo{map} to .addTo({map}) and wrap JS code in $(document).ready(function(){ ... });

Code:

import folium

m = folium.Map()

m.get_root().header.add_child(folium.CssLink('https://pasichnykvasyl.github.io/Leaflet.BigImage/src/Leaflet.BigImage.css'))
m.get_root().html.add_child(folium.JavascriptLink('https://pasichnykvasyl.github.io/Leaflet.BigImage/src/Leaflet.BigImage.js'))

png_js = '''
$(document).ready(function(){
  L.control.bigImage({position: 'topleft'}).addTo({map});
});
'''.replace("{map}", m.get_name())

m.get_root().script.add_child(folium.Element(png_js))

m

enter image description here

When using the plugin, you probably get CORS policy error displayed on console, which is an off-topic issue unrelated to the question:

Access to image at 'https://a.tile.openstreetmap.org/1/-1/1.png' from origin 'http://localhost:8888' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

2
  • That's perfect! Now I realized, that bounding every standalone Leaflet code in the JQuery function is a mandatory thing to make it working. Is that correct?
    – Geographos
    Nov 30, 2022 at 13:30
  • Not mandatory actually. It is required because folium injects the JS code to a place before the line where map object is created. Nov 30, 2022 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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