繁体   English   中英

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

[英]convert PostGIS point object to geoJSON for mapping

我有一个带有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) 

模板:

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 }};

此外,我们可以尝试下面的代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM