[英]Adding JavaScript to Folium map
我正在做一個項目,使用 folium 和 flask 制作一個 map,我正在嘗試添加我自己的 javascript 以將一些 animation 添加到磁貼中,以便一個接一個地顯示。 問題是如何使用 python flask 將我的自定義 javascript 添加到 map
正如我在下面的代碼中嘗試過的那樣:
from branca.element import Element
m = folium.Map()
map_id = m.get_name()
my_js = """
const items = document.querySelectorAll('.leaflet-interactive')
items.forEach((one) => {
one.style.visibility = 'hidden'
})
if (items.length > 0) {
if (items.length !== 0) {
let i = 0
const m = setInterval(function () {
if (i < items.length) {
items[i].style.visibility = 'visible'
i++
}
console.log('now i =' + i + ' || the number of circle = ' + items.length)
if (i === items.length) {
clearInterval(m)
console.log('now cleared')
}
}, 1000)
}
}
""".format(map_id)
e = Element(my_js)
html = m.get_root()
html.script.get_root().render()
# Insert new element or custom JS
html.script._children[e.get_name()] = e
m.save('mymap.html')
也嘗試過這樣的其他方式:
base_map.get_root().html.add_child(folium.JavascriptLink('static/custom.js'))
它注入到模板的主體但它仍然不起作用
我已經找到了如何在 js 中包含 JavaScript 和 CSS 外部鏈接:
首先,我們可以將CSS鏈接添加到頁面的標題
m.get_root().header.add_child(CssLink('./static/style.css'))
然后,這是將 JavaScript 外部鏈接插入到folium的代碼
m.get_root().html.add_child(JavascriptLink('./static/js.js'))
最后添加到之前生成的Folium腳本中
my_js = '''
console.log('working perfectly')
'''
m.get_root().script.add_child(Element(my_js))
幫助我理解如何做到這一點的資源是閱讀 throw branca 元素並檢查 Folium repo
最好使用:
對於 CSS
map.get_root().header.add_child(folium.CssLink('css/style.css'))
對於 JS
map.get_root().html.add_child(folium.JavascriptLink('js/folium.js'))
通過僅使用
m.get_root().html.add_child(JavascriptLink('./static/js.js'))
你可能會得到一個錯誤: NameError: name 'JavascriptLink' is not defined
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.