简体   繁体   中英

convert PostGIS point object to geoJSON for mapping

I have a Django app with a postgres db of PostGIS activities I'm trying to map on a frontend view using leaflet and Mapbox.

I'm serializing the activities in the view and rendering them in the template as geoJSON ( {{ props.activitiesJson|safe }} )

[can render this as html and see the JSON objects on the page].

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) 

template:

var map_activities = JSON.parse("{{ props.activitiesJson }}");
L.geoJSON(map_activities).addTo(map); 

if I render {{ props.activitiesJson }} or {{ props.activitiesJson|safe }} directly on the template (not inside a script or parsing it) I see this data structure:

{"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}]}

but trying to parse it with JSON.parse() throws a syntax err:

JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data 

how do I validly assign that geoJSON object to my map_activities var? do I need to parse it at all? (ie, var map_activities = {{ props.activitiesJson|safe }}; )

thanks

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

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

Also, we can try below code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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