javascript - 将 PostGIS 点对象转换为 geoJSON 以进行制图

标签 javascript json django postgis geojson

我有一个 Django 应用程序,其中包含 PostGIS 事件的 postgres 数据库,我正在尝试使用传单和 Mapbox 在前端 View 上进行映射。

我正在序列化 View 中的事件并在模板中将它们呈现为 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?我需要解析它吗? (即,var map_activities = {{ props.activitiesJson|safe }};)

谢谢

最佳答案

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

var map_activities = {{ props.activitiesJson|safe }};

关于javascript - 将 PostGIS 点对象转换为 geoJSON 以进行制图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52861269/

相关文章:

javascript - 具有多个值的 Mongo $addToSet 语法正确

javascript - 在 couchBase 中创建 View 时如何将输入变量设置为 json 中的键

json - ReactJS 和 django 表单

django - 在 Django : User model inheritance or use UserProfile? 中扩展用户对象

python - 支持旧的和新的 URI 版本都可以在不破坏 reverse() 的情况下工作

javascript - 从另一个组件 React js 设置状态

javascript - 在 Express.js 中从 jade 传递表单数据

web-services - 如何使用 REST Web 服务上传包含元数据的文件?

javascript - 将元素添加到愿望 list | Django

用于打开共享驱动器上的文件的 JavaScript 不起作用