Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding JavaScript to Folium map

I'm working on a project to make a map using folium and flask and I'm trying to add my own javascript to add some animation to the tile to appear one by one. The question is how can I add my custom javascript to the map using python flask

as I have tried this way in this code below:

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')

also have tried other way like this:

base_map.get_root().html.add_child(folium.JavascriptLink('static/custom.js'))

it injects to the template's body but it still doesn't work

like image 337
Ahmed Tawfik Avatar asked Mar 01 '20 21:03

Ahmed Tawfik


Video Answer


1 Answers

I already found out how to include JavaScript and CSS external link also inline js:

Firstly, way we can add CSS link to the header of the page

m.get_root().header.add_child(CssLink('./static/style.css'))

Then, this is the code to insert JavaScript External link to folium

m.get_root().html.add_child(JavascriptLink('./static/js.js'))

Finally, to add to the Folium script that been generated before

my_js = '''
console.log('working perfectly')
'''
m.get_root().script.add_child(Element(my_js))

resources that helped me to understand how to do this is reading throw branca elements and checking Folium repo

  1. Folium repo
  2. Branca Element
like image 169
Ahmed Tawfik Avatar answered Oct 21 '22 03:10

Ahmed Tawfik