python - Django 和 Folium 集成

标签 python django maps folium

这里是 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)

polls/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 }}

问题是我得到了 map 的“to_string”值(我向你保证我看到了)。那么我如何才能以实际看到 map 并定义大小的方式集成 map 呢?

enter image description here

最佳答案

为了真正将 folium 包含到自定义 django 模板中,您必须先渲染图形,然后再将其添加到上下文中(这将递归地将 map 的所有部分加载到图形中)。之后在您的模板中,您必须通过调用它们的渲染函数来分别访问图形的标题、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}

templates/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>

关于python - Django 和 Folium 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50517620/

相关文章:

python - Django 2 中的 URL 模式

python - 将 dict 字段转换为 **list** 以在 **enumarate** 中使用

javascript - 将数据从一个 Django 应用程序发送到另一个应用程序时如何保持换行符

c++ - 如何从边缘起点和终点数组构造多边形?

python - Shell 脚本从终端调用 Python 但从 Cron 调用失败

python - 在 Python/Django 中将多个 POST 请求作为多线程提交

python - django ,模型列表到字符串列表

javascript - 传单 map 标记簇不显示图标

jQuery Mobile - 如何在外部链接页面上实现 Google map

python - 在 Excel VBA 或 Python 中将 xlsx 文件转换为文件夹和子文件夹内的 xls