Skip to content

Instantly share code, notes, and snippets.

@mdiener21
Last active October 4, 2018 19:27
Show Gist options
  • Save mdiener21/284ff4b0677e5d6a28b57a0afe15a6bf to your computer and use it in GitHub Desktop.
Save mdiener21/284ff4b0677e5d6a28b57a0afe15a6bf to your computer and use it in GitHub Desktop.
Creating a Centroid in Django GeoDjango returning as GeoJson with object attributes
import json
from geojson import Feature
from django.contrib.gis.db.models.functions import Centroid, AsGeoJSON
from buildings.models import Space
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def get_room_center(request, unique_id):
space_qs = Space.objects.filter(external_id=unique_id)
att = space_qs.values()[0]
# do NOT include the original polygon geometry, so set it to None
if att['multi_poly']:
att['multi_poly'] = None
centroid_result = Space.objects.annotate(json=AsGeoJSON(Centroid('multi_poly'))).get(external_id=unique_id).json
res = Feature(geometry=json.loads(centroid_result), properties=att)
# or
# res = Feature(geometry=json.loads(space_qs.multi_poly.centroid.geojson), properties=att)
return Response(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment