![](/img/trans.png)
[英]How to convert data from PostGIS database into GeoJSON in Java
[英]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.