gpt4 book ai didi

python - Django - 以geoJSON格式获取多边形的质心

转载 作者:太空宇宙 更新时间:2023-11-03 16:03:26 25 4
gpt4 key购买 nike

我正在构建一个 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. 向我的模型添加一个列质心:我不想这样做
  2. 创建我的模型的数据库 View :Django 不管理数据库 View ,我不想编写自定义迁移
  3. 使用相同的模型并在我的 orm 语句中添加一个 extra(...):我尝试过,但在序列化期间或之前事情变得很困难,因为在模型中类型是Polygon,质心是Point。错误如下:

    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. AsGeoJSON , 哪个

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

  2. Centroid() 哪个

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

  3. .annotate() 哪个

    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.

<小时/>

示例:

以下查询:

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

将添加一个名为 'geometry' 的字段到Polygon查询集将包含从 coordinates 计算出的质心每个领域Polygon您给定模型的对象。

关于python - Django - 以geoJSON格式获取多边形的质心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40083521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com