将PostGIS点对象转换为geoJSON以进行映射

Chr*_* B. 5 javascript django json postgis geojson

我有一个带有postgres db of PostGIS活动的Django应用程序我正在尝试使用传单和Mapbox在前端视图上进行映射.

我正在序列化视图中的活动并将其作为geoJSON({{ props.activitiesJson|safe }})在模板中呈现

[可以将其渲染为html并查看页面上的JSON对象].

views.py(ex)

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) 
Run Code Online (Sandbox Code Playgroud)

模板:

var map_activities = JSON.parse("{{ props.activitiesJson }}");
L.geoJSON(map_activities).addTo(map); 
Run Code Online (Sandbox Code Playgroud)

如果我渲染{{ 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}]}
Run Code Online (Sandbox Code Playgroud)

但尝试使用JSON.parse()解析它会引发语法错误:

JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data 
Run Code Online (Sandbox Code Playgroud)

如何有效地将geoJSON对象分配给我的map_activities var?我需要解析它吗?(即var map_activities = {{ props.activitiesJson|safe }};)

谢谢

Chr*_* B. 1

最终(不确定这是否是最佳实践)对我来说正确的方法是根本不解析 geoJSON 对象并将其直接传递给变量

var map_activities = {{ props.activitiesJson|safe }};
Run Code Online (Sandbox Code Playgroud)