Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert Postgres geometry format to WKT

I have a Postgres table which stores polygon geometry in its specific format in one of the column, something like this-

0103000020E61000000100000004000000B8627F336B1554405DD602FFA2733A40B8627FA7601554403851F8EBC7723A40B8627FC38F15544036D539E90B733A40B8627F336B1554405DD602FFA2733A40

I know how to convert this single value to WKT using ST_AsText which will give me POLYGON((Lat Long)). But I want to convert whole column into WKT format.

How to achieve this?

Thanks!

like image 407
J. Doe Avatar asked Dec 06 '22 12:12

J. Doe


1 Answers

Have you tried this?

SELECT ST_AsText(your_geom_column) FROM your_table

In the following examples I'll show you a few ways to serialise your geometries. Here is sample data with two points encoded as 4326 (WGS84):

CREATE TEMPORARY TABLE tmp 
  (geom GEOMETRY);
INSERT INTO tmp VALUES 
  ('SRID=4326;POINT(1 2)'),
  ('SRID=4326;POINT(2 4)');

Geometries as WKB (Well-Known Binary, default):

SELECT geom FROM tmp;

 geom                        
----------------------------------------------------
 0101000020E6100000000000000000F03F0000000000000040
 0101000020E610000000000000000000400000000000001040

Geometries as WKT (Well-Known Text) and EWKT (WKT with an explicit Spatial Reference System):

SELECT ST_AsText(geom), ST_AsEWKT(geom) FROM tmp;

 st_astext  | st_asewkt       
------------+----------------------
 POINT(1 2) | SRID=4326;POINT(1 2)
 POINT(2 4) | SRID=4326;POINT(2 4)

In case you fancy GeoJSON

SELECT ST_AsGeoJSON(geom) FROM tmp;

 st_asgeojson             
--------------------------------------
 {"type":"Point","coordinates":[1,2]}
 {"type":"Point","coordinates":[2,4]}

Or even GML

SELECT ST_AsGML(geom) FROM tmp;

 st_asgml                                      
-----------------------------------------------------------------------------------
 <gml:Point srsName="EPSG:4326"><gml:coordinates>1,2</gml:coordinates></gml:Point>
 <gml:Point srsName="EPSG:4326"><gml:coordinates>2,4</gml:coordinates></gml:Point>

The Google Earth enthusiasts also have their fun! Geometries as KML

SELECT ST_AsKML(geom) FROM tmp;

 st_askml                    
-----------------------------------------------
 <Point><coordinates>1,2</coordinates></Point>
 <Point><coordinates>2,4</coordinates></Point>

And the list goes on! In the PostGIS documentation there are other fancy ways to serialise geometry.

Demo: db<>fiddle

like image 184
Jim Jones Avatar answered Dec 14 '22 22:12

Jim Jones