为什么 GeoDjango 不在 SRID 4326 中返回我的 GeoJSON?

Why is GeoDjango not returning my GeoJSON in SRID 4326?

我有一个模型,其点数据存储在 srid 2953 中。 当我序列化这些数据时,我假设 GeoDjando 会通过将坐标转换为 SRID 4326 将其转换为有效的 GeoJSON。 也许我需要特别告诉它转换这个? 根据我的阅读,我了解到 CRS 已从 GeoJSON 中贬值,并且它仅在 SRID 4326 中有效?

class Hpnrecord(models.Model):
    ...
    geom = models.PointField(srid=2953, null=True)

稍后在序列化程序中我有:

class HpnrecordSerializer(serializers.GeoFeatureModelSerializer):
    class Meta:
        fields = "__all__"
        geo_field = "geom"
        model = Hpnrecord

当我查看返回的数据时,我得到了这个:

{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 2594598.985, 7425392.375 ] }, "properties": { } },

如您所见,坐标显示为东向和北向(与模型中存储的相同),而不是转换为 SRID 4326。我的端点期望在 srid 4326 中接收到它。

如何指定我希望序列化在 SRID 4326 中?

您可能已经注意到,SRID 转换不会自动完成。我有 2 个建议给你:

建议一:将数据存储在想要的SRID

在存储数据之前,首先将其转换为所需的 4326 srid。您的模型将更改:

class Hpnrecord(models.Model):
    ...
    geom = models.PointField(srid=4326, null=True)

存储数据如下所示:

from django.contrib.gis.geos import Point

...

point = Point(x, y, srid=2953)
point.transform(4326)
model_instance.geom = point
model_instance.save()

建议2:使用serializer的to_representation()

您保持模型原样,并使用序列化程序的 to_representation() 方法动态转换 SRID,请参阅 docs。请注意,即时转换它会导致速度下降,但您可以保留模型原样。

class HpnrecordSerializer(serializers.GeoFeatureModelSerializer):
    class Meta:
        fields = "__all__"
        geo_field = "geom"
        model = Hpnrecord
    
    def to_representation(self, instance):
        """Convert `geom` to srid 4326."""
        ret = super().to_representation(instance)
        ret['geom'] = ret['geom'].transform(4326)
        return ret