如何反序列化GeoServer WFS GeoJSON?

2024-06-16 09:51:41 发布

您现在位置:Python中文网/ 问答频道 /正文

TL:DR
我想将GeoJSON格式的GeoServer WFS FeatureCollection反序列化为GeometryField/GeometryCollection。在


让我们从模型开始:

class Layer(models.Model):
    name = models.CharField(max_length=50)
    layer = GeometryCollectionField(null=True)

以及序列化程序:

^{pr2}$

现在,WFS GeoJSON示例如下所示:

{
  "type": "FeatureCollection",
  "totalFeatures": 1,
    "features": [
      {
        "type": "Feature",
        "id": "some_id",
        "geometry": {
          "type": "MultiLineString",
          "coordinates": [
            [
              [4.538638998513776, 50.4674721021459],
              [4.5436667765043754, 50.47258379613634],
              [4.548444318495443, 50.47744374212726], 
              ...     
        },
        "geometry_name": "the_geom",
        "properties": {
          ...
        }
      }
    ],
    "crs": {
      "type": "name",
      "properties": {
        "name": "urn:ogc:def:crs:EPSG::4326"
      }
    }
  }
}

在尝试反序列化上述内容时,我得到以下错误:

"layer": [
  "Unable to convert to python object: 
  Invalid geometry pointer returned from \"OGR_G_CreateGeometryFromJson\"."
]

PS:我更喜欢一个不需要修改GeoJSON以将其转换为GeometryCollection的解决方案(如果存在的话),正如我成功地完成的那样。在


Tags: tonamelayerid序列化modelsgeojsontype
0条回答
网友
1楼 · 发布于 2024-06-16 09:51:41

我也遇到过类似的情况。我想问题是解析GeoJSON,因为它被转换成了Python字典。我使用json.dump将其恢复为JSON格式。在

我就是这样解决我的问题的。首先是为GIS字段生成一个字段序列化器。在我的例子中,我使用了GeoGeometry:

#serializers.py
from django.contrib.gis.geos import GEOSGeometry
import json

class GeometryFieldSerializer(serializers.Field):
    def to_representation(self, instance):
        if instance.footprint:
            instance = json.loads(instance.footprint.geojson)
        else:
            instance = None
        return instance

    def to_internal_value(self, data):
        data = str(json.dumps(data))
        meta = {"footprint": GEOSGeometry(data)}
        return meta

在此之后,您可以将其合并到主序列化程序中。例如:

^{pr2}$

这是我要发布的JSON示例:

{"name": "test",
"footprint": {"type": "Polygon",
              "coordinates": [[ [121.37, 14.02], [121.62, 14.02], 
                                [121.62, 14.26], [121.37, 14.26], 
                                [121.37, 14.02] ]]}
}
网友
2楼 · 发布于 2024-06-16 09:51:41

@Nikko有一个非常好的面向DRF的解决方案!

实际上,我以一种非常类似的方式解决了这个问题,通过为geoserver的特定响应创建一个解析器,它从features返回一个geos.GeometryCollection

def parse_feature_collection(feature_collection: dict):
    """
    Parses a WFS response from GeoServer and creates a GeometryCollection from it.
    """
    geometries = [
        GEOSGeometry(json.dumps(feature.get('geometry')))
        for feature in feature_collection.get('features')
    ]
    return GeometryCollection(tuple(geometries), srid=4326)

然后在一个celery任务中使用它来更新相应的模型字段,并在实例上执行一些其他耗时的方法(栅格化数据并应用一些计算)。在

相关问题 更多 >