Django - 获取geoJSON格式多边形的中心点

3

我正在构建一个用于管理地理相关数据的REST API。
我的前端开发人员希望根据缩放级别以geoJSON格式检索多边形的质心。

我的多边形模型如下:

...
from django.contrib.gis.db import models as geomodels
class Polygon(geomodels.Model):
    fk_owner = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True)
    external_id = models.CharField(max_length=25, unique=True) 
    func_type = models.CharField(max_length=15)
    coordinates = geomodels.PolygonField(srid=3857)
    properties = JSONField(default={}) 

该 API 目前返回类似以下内容:

"type": "FeatureCollection",
"features": [
 {
     "type": "Feature",
     "geometry": {
         "type": "Polygon",
         "coordinates": [[[..]]]
      }
  }]

我使用rest_framework_gis.serializers.GeoFeatureModelSerializer来序列化我的数据。

我看到以下几种方法可以获取质心:

  1. Add a column centroid to my model: I don't want to do this
  2. Create a database view of my model: Django does not manage database views and I don't want to write a custom migration
  3. Use the same model and add an extra(...) to my orm statement: I tried but things get hard in or before serialization, because in the model the type is Polygon, and the centroid is a Point. The error is the following:

    TypeError: 
        Cannot set Polygon SpatialProxy (POLYGON) with value of type:
        <class 'django.contrib.gis.geos.point.Point'>
    
预期输出应为:
"type": "FeatureCollection",
"features": [
 {
     "type": "Feature",
     "geometry": {
         "type": "Point",
         "coordinates": [..]
      }
  }]

您的意见是什么?

1个回答

5
你可以使用以下方法的组合:
  1. AsGeoJSON,它

    接受单个地理字段或表达式,并返回几何图形的GeoJSON表示。

  2. Centroid(),它

    接受单个地理字段或表达式,并返回几何图形的质心值。

  3. .annotate(),它

    注释查询集中的每个对象,使用提供的查询表达式列表。
    [...]
    annotate() 的每个参数都是一个注释,将添加到返回的 QuerySet 中的每个对象中。


示例:

以下查询:

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

将在Polygon查询集中添加一个名为'geometry'的字段,该字段将包含从给定模型的每个Polygon对象的coordinates字段计算得出的质心。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接