我有一个Django应用程序,它具有PostGIS活动的postgres数据库,我正尝试使用传单和Mapbox映射到前端视图上。
我正在序列化视图中的活动并将其在模板中呈现为geoJSON({{ props.activitiesJson|safe }}
)
[可以将其呈现为html并在页面上查看JSON对象]。
views.py(例如)
def map(request):
mapbox_key = settings.MAPBOX_API_KEY
activities = Activity.get_activities_near(lat, lng, radius)
props = {'activitiesJson' : serializers.serialize('geojson', activities),}
context = {
'props' : props,
'mapbox_key': mapbox_key
}
return render(request, 'app/map.html', context)
模板:
var map_activities = JSON.parse("{{ props.activitiesJson }}");
L.geoJSON(map_activities).addTo(map);
如果我直接在模板上渲染{{ props.activitiesJson }}
或{{ props.activitiesJson|safe }}
(而不是在脚本内部或对其进行解析),我会看到以下数据结构:
{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"cause": 1, "name": "Test Action", "slug": "test-action", "is_active": true, "image": "test.jpeg", "description": "test description", "date_start": null, "date_end": null, "skills_required": false, "on_site": false, "address_street": "123 Main St.", "address_street_2": "", "address_city": "New York", "address_state": "NY", "address_zip": "10013", "address_country": "", "location_city": "", "location_state": "", "location_country": "", "skills_list": [], "pk": "1"}, "geometry": null}]}
但是尝试使用JSON.parse()解析它会抛出语法错误:
JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
如何将那个geoJSON对象有效地分配给我的map_activities变量?我是否需要解析它? (即var map_activities = {{ props.activitiesJson|safe }};
)
谢谢
答案 0 :(得分:1)
最终(不确定这是否是最佳实践)对我来说正确的方法是根本不解析geoJSON对象并将其直接传递给变量
var map_activities = {{ props.activitiesJson|safe }};
答案 1 :(得分:0)
此外,我们可以尝试以下代码。
def map(request):
activities = Activity.get_activities_near(lat, lng, radius)
activitiesData = []
for activity in activities:
listdata = {'id': activity.id, 'name': activity.name} # As per requirement
activitiesData.append(listdata)
response = HttpResponse(json.dumps(activitiesData))
return response