Django新手:我的目标是将Folium集成到html页面中。所以我现在拥有的是:
polls/views.py
def show_map(request):
#creation of map comes here + business logic
m = folium.Map([51.5, -0.25], zoom_start=10)
test = folium.Html('<b>Hello world</b>', script=True)
popup = folium.Popup(test, max_width=2650)
folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m)
context = {'my_map': m}
return render(request, 'polls/show_folium_map.html', context)民意调查/urls.py
urlpatterns = [
path('show_my_map', views.show_map, name='show_map'),]
和show_folium_map.html
<h1>map result comes here</h1>
{{ my_map }}问题是,我得到了地图的'to_string‘值(我向您保证,我预见到了)。那么,我如何以这样的方式集成地图,使我能够真正地看到地图并定义大小呢?

发布于 2019-11-08 14:13:09
为了真正地将folium包含到定制django模板中,您必须在将其添加到上下文之前先呈现您的图形(这将递归地将映射的所有部分加载到图中)。之后,在模板中,您必须分别访问图中的头、html和脚本部分,方法是调用它们的呈现函数。此外,这些部分必须被django模板标记标记为“安全”,以便允许html插入。见下面的例子。
示例:
views.py:
import folium
from django.views.generic import TemplateView
class FoliumView(TemplateView):
template_name = "folium_app/map.html"
def get_context_data(self, **kwargs):
figure = folium.Figure()
m = folium.Map(
location=[45.372, -121.6972],
zoom_start=12,
tiles='Stamen Terrain'
)
m.add_to(figure)
folium.Marker(
location=[45.3288, -121.6625],
popup='Mt. Hood Meadows',
icon=folium.Icon(icon='cloud')
).add_to(m)
folium.Marker(
location=[45.3311, -121.7113],
popup='Timberline Lodge',
icon=folium.Icon(color='green')
).add_to(m)
folium.Marker(
location=[45.3300, -121.6823],
popup='Some Other Location',
icon=folium.Icon(color='red', icon='info-sign')
).add_to(m)
figure.render()
return {"map": figure}模板/folium_app/map.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{{map.header.render|safe}}
</head>
<body>
<div><h1>Here comes my folium map:</h1></div>
{{map.html.render|safe}}
<script>
{{map.script.render|safe}}
</script>
</body>
</html>发布于 2020-04-02 15:26:35
你可以试试下面的方法。我也面临过同样的问题,这对我很有帮助。
views.py
def show_map(request):
#creation of map comes here + business logic
m = folium.Map([51.5, -0.25], zoom_start=10)
test = folium.Html('<b>Hello world</b>', script=True)
popup = folium.Popup(test, max_width=2650)
folium.RegularPolygonMarker(location=[51.5, -0.25], popup=popup).add_to(m)
m=m._repr_html_() #updated
context = {'my_map': m}
return render(request, 'polls/show_folium_map.html', context)show_folium_map.html
{{ my_map|safe }}发布于 2019-01-13 21:52:24
通过触发Map的(内部)父级呈现,可以将html作为字符串获得。
m = folium.Map()
html: str = m.get_root().render()请注意,这将返回一个完整的html页面,因此您可能需要将其放入一个iframe中。
或者,您可以分别呈现头部、正文和脚本部分。这样,您就可以将每个部分放在属于它的页面上,而不需要一个iframe:
m = folium.Map()
html_head: str = m.get_root().header.render()
html_body: str = m.get_root().html.render()
html_script: str = m.get_root().script.render()https://stackoverflow.com/questions/50517620
复制相似问题