我正在构建一个REST来管理与地理相关的数据。
我的前端开发人员希望以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来序列化我的数据。
我看到了以下获得质心的方法:
extra(...):我试过了,但是在序列化中或序列化之前,事情变得很困难,因为在模型中,类型是Polygon__,而质心是Point__。错误如下:
TypeError:无法设置值为的多边形SpatialProxy (多边形)预期产出应是:
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [..]
}
}]你的意见是什么?
发布于 2017-06-19 09:20:20
您可以使用以下方法的组合:
AsGeoJSON,它接受单个地理字段或表达式,并返回几何的GeoJSON表示。Centroid(),它接受单个地理字段或表达式,并返回几何图形的质心值。.annotate(),它用提供的查询表达式列表对QuerySet中的每个对象进行注释。
..。
annotate()的每个参数都是一个注释,它将添加到返回的QuerySet中的每个对象中。示例:
以下查询:
Polygon.objects.annotate(geometry=AsGeoJSON(Centroid('coordinates')))将向'geometry'查询集添加一个名为Polygon的字段,该字段将包含根据给定模型的每个Polygon对象的coordinates字段计算的质心。
https://stackoverflow.com/questions/40083521
复制相似问题