[Django]-Django โ€“ Get centroid of polygon in geoJSON format

5๐Ÿ‘

โœ…

You can use a combination of the following methods:

  1. AsGeoJSON, which

    Accepts a single geographic field or expression and returns a GeoJSON representation of the geometry.

  2. Centroid() which

    Accepts a single geographic field or expression and returns the centroid value of the geometry.

  3. .annotate() which

    Annotates each object in the QuerySet with the provided list of query expressions.
    [โ€ฆ]
    Each argument to annotate() is an annotation that will be added to each object in the QuerySet that is returned.


Example:

The following query:

Polygon.objects.annotate(geometry=AsGeoJSON(Centroid('coordinates')))

will add a field named 'geometry' to the Polygon queryset which will contain the centroid calculated from the coordinates field of every Polygon object of your given model.

๐Ÿ‘คJohn Moutafis

Leave a comment