Skip to content Skip to sidebar Skip to footer

Extract The Coordinates From The Linestringfield

I've this simple model from GeoDjango for a line vector: from django.contrib.gis.db import models class LineBuffer(models.Model): geom = models.LineStringField()

Solution 1:

Well doing a simple post mortem in the error, we can plainly see that the response of the coordinates property needs to be refactored to fit your needs.

I would suggest using the geom.coords property to access and manipulate the LineString's coordinates. Django's LineString coords will look like this: ((x_0, y_0), (x_1, y_1), ...) so it is quite clear what we need to do:

@propertydefcoordinates(self):
    return [list(coord_pair) for coords_pair inself.geom.coords]

and from the template, we need to omit the list cast when we use the coordinates property:

var data_source = {
    "type": "FeatureCollection",
    "features": [{% for d in geometry %}
        {
        "type": "Feature",
        "properties": {
            "pk": "{{ d.pk }}"
        },
        "geometry": {
            "type": "LineString",
            "coordinates": {{ d.coordinates }}
        }
        {% if forloop.last %}} {% else %}}, {% endif %}{% endfor %}
    ]
}

Doing your own serialization in this specific case has no benefit that I can see and I would suggest refactoring your process altogether to utilize the GeoJson Serializer:

from django.core.serializers import serialize

defline_mapbox_turf_buffer(request):
    context = {
        'geometry': serialize(
            'geojson', 
            LineBuffer.objects.all(),
            geometry_field='geom',
        )
    }
    template = 'buffer/reading/line_mapbox_turf_buffer.html'return render(request, template, context)

and in the template simply access the geometry context field:

var data_source = {{ geometry }}

Post a Comment for "Extract The Coordinates From The Linestringfield"