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? (i.e., var map_activities = {{ props.activitiesJson|safe }};
)
thanks
ultimately (not sure if this is best practice) the right approach for me was not parsing the geoJSON object at all and passing it straight to the variable
var map_activities = {{ props.activitiesJson|safe }};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With