Python Folium – Fix Leaflet Plugin Not Visible on Map

foliumjavascriptleafletpython

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?

Best Answer

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.