Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions docs/flask.rst
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
Using folium with flask
=======================

A very common use case is to use folium with in a flask app.
The trick is to return folium's HTML representation.
Here is an example on how to do that:
A common use case is to use folium in a flask app. There are multiple ways you
can do that. The simplest is to return the maps html representation. If instead
you want to embed a map on an existing page, you can either embed an iframe
or extract the map components and use those.

Below is a script containing examples for all three use cases:

.. literalinclude:: ../examples/flask_example.py
70 changes: 65 additions & 5 deletions examples/flask_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,78 @@

"""

from flask import Flask
from flask import Flask, render_template_string

import folium

app = Flask(__name__)


@app.route("/")
def index():
start_coords = (46.9540700, 142.7360300)
folium_map = folium.Map(location=start_coords, zoom_start=14)
return folium_map._repr_html_()
def fullscreen():
"""Simple example of a fullscreen map."""
m = folium.Map()
return m.get_root().render()


@app.route("/iframe")
def iframe():
"""Embed a map as an iframe on a page."""
m = folium.Map()

# set the iframe width and height
m.get_root().width = "800px"
m.get_root().height = "600px"
iframe = m.get_root()._repr_html_()

return render_template_string(
"""
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Using an iframe</h1>
{{ iframe|safe }}
</body>
</html>
""",
iframe=iframe,
)


@app.route("/components")
def components():
"""Extract map components and put those on a page."""
m = folium.Map(
width=800,
height=600,
)

m.get_root().render()
header = m.get_root().header.render()
body_html = m.get_root().html.render()
script = m.get_root().script.render()

return render_template_string(
"""
<!DOCTYPE html>
<html>
<head>
{{ header|safe }}
</head>
<body>
<h1>Using components</h1>
{{ body_html|safe }}
<script>
{{ script|safe }}
</script>
</body>
</html>
""",
header=header,
body_html=body_html,
script=script,
)


if __name__ == "__main__":
Expand Down