How can I create a polygon using fields in PostgreSQL?

强颜欢笑 提交于 2019-12-04 00:58:26

问题


I have 8 real values in a table that I'd like to combine into a polygon. I haven't been able to figure out how to create a polygon using these values though. I keep trying variations of

SELECT polygon(lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4) FROM table;

but keep getting errors about the polygon function not existing or an invalid input syntax for type polygon. Has anyone done this before?


回答1:


The syntax for a regular postgres polygon is more like:

insert into geo_table values (1, '((2,2),(3,4),(3,6),(1,1))');

Where 1 is some id and the quoted entry is the polygon. I would expect the query to be similar, you probably need parentheses etc for the coordinates. Typically for geospatial data you want (Lon Lat) coordinates. Postgis also takes WKT statements like:

GeomFromText('POLYGON((long1 lat1, long2 lat2, long3 lat3))')




回答2:


As mentioned by bvmou - GeomFromText will work fine. I'll just add a small syntax update:

GeomFromText('POLYGON((long1 lat1, long2 lat2, long3 lat3))')



回答3:


This example takes longitude and latitude coordinates from a table and converts them into a geometry. The dimensions of each box are given as long_high, long_low, lat_high, and lat_low. Here, a box of approximately 500m by 500m.

  1. Add a new geometry column 'box' to the table

    SELECT AddGeometryColumn('public', 'predpol_raw', 'box', 2240, 'POLYGON', 2);
  2. Update the new field with those values.

    UPDATE predpol_raw
    SET box =
            ST_Transform(
                ST_GeomFromText(
                    format('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))',
                        long_high,lat_high, long_low,lat_high,
                        long_low,lat_low, long_high,lat_low,
                        long_high,lat_high
                    ),
                    4326
                ),
                2240
            );
    

Note the transformation to a different spatial reference. The POLYGON keyword requires double parentheses '(( ))'.



来源:https://stackoverflow.com/questions/1105757/how-can-i-create-a-polygon-using-fields-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!