0

I want to use POSTGIS function ST_AsMVTGeom with django ORM. Therefore I create following geo function:

from django.contrib.gis.db.models.functions import Transform, GeoFunc

class AsMVTGeom(GeoFunc):
    function = "ST_AsMVTGeom"
    geom_param_pos = (0, )
    output_field = GeometryField(srid=4326)

and call it with following query (example bounding box):

mvt_geom = (
        municipality.objects
        .annotate(
            mvt_geom=AsMVTGeom(
                Transform("geom", 3857),
                Value("ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096))"),
                4096,
                0,
                False,
            )
        )
    )
    print(str(mvt_geom.query))

This gives me something like this (for simple model containing a geom column):

SELECT "map_municipality"."id", "map_municipality"."ags", "map_municipality"."nuts", "map_municipality"."name", "map_municipality"."type", ST_AsMVTGeom(ST_Transform("map_municipality"."geom", 3857), ST_MakeBox2D(ST_Point(0, 0), ST_Point(4096, 4096)), 4096, 0, False)::bytea AS "mvt_geom" FROM "map_municipality"

But as I want to use outcome in further queries, I need type of mvt_geom to be geometry not bytea. If I remove casting to bytea, everything is fine. I somehow cannot change it to type geometry, trying for hours... Even explicit casting to GeometryField does not help.

This user seems to have a similar problem: https://stackoverflow.com/q/56475858/5804947

3
  • 1
    MapBox vector tile geometry is not PostGIS geometry. If you need geometry type in further processing, don't use AsMVTGeom. You have geometries already in the geom column.
    – user30184
    Nov 16 '20 at 13:17
  • In fact, i want to use above query as subquery to the following query: model.objects.annotate(mvt=AsMVT(Subquery(mvt_geom), Value("default"), 4096, Value("mvt_geom"))) This only works if I remove ::bytea from raw query. How can I use above query as subquery?
    – Henhuy
    Nov 16 '20 at 13:25
  • I guess that by dropping out AsMVT Geom from the subquery mvt_geom=AsMVTGeom(.... As you can read postgis.net/docs/ST_AsMVTGeom.html takes in geometries so must feed it with geometries.
    – user30184
    Nov 16 '20 at 13:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.