我有一个带有PosGIS后端的简单应用程序。我希望数据库中每个功能都有一个页面。我使用了一个子弹和URL路由。
PostGIS要素在geom列中存储了一个多边形,使用geodjango将其建模为MultiPolygonField。
将这个geom列解析为geojson以便将其添加到传单地图的最简单方法是什么?
下面是我的代码,尽管我在页面上收到此错误代码,但我尝试使用geojson序列化程序。
from django.shortcuts import render
from Countries_App.models import Countries
from django.core.serializers import serialize
# Create your views here.
def show_country(request, country_slug):
# Create a context dictionary which we can pass
# to the template rendering engine.
context_dict = {}
try:
# Can we find a category name slug with the given name?
# If we can't, the .get() method raises a DoesNotExist exception.
# So the .get() method returns one model instance or raises an exception.
country = Countries.objects.get(slug=country_slug)
Country_geojson = serialize('geojson',
Countries.objects.get(slug=country_slug))
# We also add the category object from
# the database to the context dictionary.
# We'll use this in the template to verify that the category exists.
context_dict['Countries'] = country
except KeyError:
country = []
context_dict['Countries'] = Countries
country_slug = none
Country_geojson = serialize('geojson',
Country.objects.filter(name=country_slug))
# Go render the response and return it to the client.
return render(request, 'Countries_App/country.html', {'context_dict':
context_dict, 'Country_geojson': Country_geojson})
urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^country/(?P<country_slug>[\w\-]+)/$',
GeoJSONLayerView.as_view(model=Countries), name='data'),
url(r'^country/(?P<country_slug>[\w\-]+)/$', views.show_country,
name='show_country'),
]
我尝试将geojson添加到传单地图的模板摘录
var geojsonfeature = '{{ Countries_geojson }}'
L.geoJSON(geojsonFeature).addTo(map);
我以正确的方式来处理这个问题吗?将PostGIS多边形几何简单添加到模板的最简单方法是什么?请记住,我只想添加与子弹匹配的特征的几何形状。
答案 0 :(得分:1)
在django-geojson's documentation中,有关于如何在django模板中使用模块标签的参考:
主要用于在HTML输出中转储功能并绕过AJAX调用:
// Leaflet JS L.geoJson({{ object_list|geojsonfeature|safe}}).addTo(map);
可用于模型,几何字段或查询集。
{% load geojson_tags %} var feature = {{ object|geojsonfeature|safe }}; var geom = {{ object.geom|geojsonfeature|safe }}; var collection = {{ object_list|geojsonfeature|safe }};
可以提供属性和自定义几何字段名称。
{{ object|geojsonfeature:"name,age" }} {{ object|geojsonfeature:"name,age:the_geom" }} {{ object|geojsonfeature:":geofield" }}