Spatial

在 PostGIS 中,如何交換無效點的緯度/對數,例如 MySQL ST_SwapXY?

  • June 22, 2018

MySQL 有一個ST_SwapXY交換xy值(long 和 lat)的函式。如果您不正確地導入數據,一個函式(如ST_SetSRID)很有用。

接受內部幾何格式的參數,交換幾何內每個座標對的 X 和 Y 值,並返回結果。

我如何在 PostGIS 中執行此操作?

使用 PostGIS,您將使用訪問器ST_X()ST_Y(),並使用建構子重新創建該點,ST_MakePoint(x,y)例如:

SELECT ST_AsText(geom) AS old, ST_AsText(newgeom) AS new
FROM ( VALUES (ST_MakePoint(0,1)) ) AS t(geom)
CROSS JOIN LATERAL
 ST_SetSRID(  ST_MakePoint(ST_Y(geom),ST_X(geom)), ST_SRID(geom)  )
AS t2(newgeom);
   old     |    new     
------------+------------
POINT(0 1) | POINT(1 0)
(1 row)

您可以創建一個簡單的函式_ST_SwapXY來在點上完成此操作。

CREATE FUNCTION _ST_SwapXY(geom geometry(point))
RETURNS geometry(point) AS $$
 SELECT ST_SetSRID(  ST_MakePoint(ST_Y(geom),ST_X(geom)), ST_SRID(geom)  );
$$ LANGUAGE sql
IMMUTABLE;

CREATE FUNCTION _ST_SwapXY(geog geography(point))
RETURNS geography(point) AS $$
 SELECT ST_SetSRID(  ST_MakePoint(ST_Y(geog::geometry),ST_X(geog::geometry)), ST_SRID(geog)  )::geography;
$$ LANGUAGE sql
IMMUTABLE;

在地理和幾何對像上測試它(EWKT擴展眾所周知的文本 (WKT) 以包含 SRID。)

SELECT ST_AsEWKT(pt) AS orig,
 ST_AsEWKT(  _ST_SwapXY(pt::geometry)   ) AS geom,
 ST_AsEWKT(  _ST_SwapXY(pt::geography)  ) AS geog
FROM ( VALUES
 (ST_MakePoint(0,1)),
 (ST_SetSRID(ST_MakePoint(0,1),4326))
) AS t(pt);
        orig         |         geom         |         geog         
----------------------+----------------------+----------------------
POINT(0 1)           | POINT(1 0)           | SRID=4326;POINT(1 0)
SRID=4326;POINT(0 1) | SRID=4326;POINT(1 0) | SRID=4326;POINT(1 0)

注意:MySQL 的ST_SwapXY()LINESTRINGS覆蓋能力也大大POLYGON增強,但希望您的結構不會在內部搞砸。如果他們是你將不得不遞歸地這樣做。

引用自:https://dba.stackexchange.com/questions/210330