Every time I create a folium map with python it saves however erases all JavaScript code I have coded to the map.html document. How can I stop this? I want my own JavaScript into the folium map.
Cheers :)
CodePudding user response:
Documentation shows Using folium with flask and there you can see function ._repr_html_()
This function gives HTML
which you can put in own HTML
and save all in file.
import folium
m = folium.Map(location=[45.5236, -122.6750])
folium_html = m._repr_html_()
html = f"""
<!DOCTYPE html>
<html>
<body>
<h1>STACKOVERFLOW EXAMPLE</h1>
{folium_html}
<script>alert('My JavaScript Code');</script>
</body>
</html>
"""
with open('map.html', 'w') as fh:
fh.write(html)
EDIT:
I found that m._repr_html_()
is used to generate iframe
for Jupyter
but original save()
uses m.get_root().render()
to get full HTML
. But there are other functions to get separatelly parts for head
, body
, script
(which render()
uses to generate full HTML
) and it can be used to generate own HTML
.
import folium
m = folium.Map(location=[45.5236, -122.6750])
root = m.get_root()
#print(root.render()) # used by `save()`
folium_head = root.header.render()
folium_body = root.html.render()
folium_script = root.script.render()
html = f"""
<!DOCTYPE html>
<html>
<head>
{folium_head}
</head>
<body>
<h1>STACKOVERFLOW EXAMPLE</h1>
{folium_body}
<script>
{folium_script}
alert('My JavaScript Code');
</script>
</body>
</html>
"""
with open('map.html', 'w') as fh:
fh.write(html)
EDIT:
It seems you can add elemenets also to code generated by save()
import folium
m = folium.Map(location=[45.5236, -122.6750])
root = m.get_root()
# add to `<head>` before folium elements
#root.header.add_child(folium.Element("<style> ... </style>"))
# add to `<body>` before folium elements
root.html.add_child(folium.Element("<h1>STACKOVERFLOW EXAMPLE</h1>"))
# add to `<script>` before folium elements
#root.script.add_child(folium.Element("alert('My JavaScript Code');"))
# add folium elements
#root.render() # used by `save()`
m.render() # used by `save()`
# add to `<head>` after folium elements
#root.header.add_child(folium.Element("<style> ... </style>"))
# add to `<body>` after folium elements
#root.html.add_child(folium.Element("<h1>STACKOVERFLOW EXAMPLE</h1>"))
# add to `<script>` after folium elements
root.script.add_child(folium.Element("alert('My JavaScript Code');"))
m.save('test.html')