Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? (i.e., var map_activities = {{ props.activitiesJson|safe }};)

thanks

like image 460
Chris B. Avatar asked Nov 07 '22 01:11

Chris B.


1 Answers

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 }};
like image 184
Chris B. Avatar answered Nov 12 '22 11:11

Chris B.