How do I convert a latitude/longitude pair into a PostGIS geography type?

只愿长相守 提交于 2020-05-09 17:54:22

问题


I'm trying to load a bunch of latitude/longitude pairs into a PostGIS geography type so as to be able to query by location.

In particular I have a table with float latitude and longitude columns and a geography(Point, 4326) column. I would like to do

update mytable set geography = ???

The documentation appears to suggest that the following should work:

update mytable set geography = ST_GeogFromText('POINT(' || latitude || ' ' ||
                                                           longitude || ')');

It doesn't. I don't know what it's interpreting this point as meaning, but it only allows the longitude to lie between -90 and 90, so it's clearly not a longitude.

So, what do I do?


回答1:


...sigh. Stupidity on my part. Apparently the correct order is longitude, latitude. I was fooled into thinking that both coordinates had the same range (-180 to 180) so thought something more subtle was going on.




回答2:


Here are some ways to make geography types:

  1. Convert numeric long and lat columns to a geog geography type:

    UPDATE mytable SET geog = ST_SetSRID(ST_MakePoint(long, lat), 4326)::geography
    
  2. Convert a geom geometry column (SRID=4326) to a geog geography type using a simple cast:

    UPDATE mytable SET geog = geom::geography
    
  3. Transform a projected geom geometry column to a geog geography type:

    UPDATE mytable SET geog = ST_Transform(geom, 4326)::geography
    

Note that the last two examples work on any geometry type. Also, the conversion from geometry to geography is often implicit, and these examples work without ::geography, however explicit casts are usually a good practice for these things.




回答3:


To perform exchange between lat and lng you may use:

update mytable set geography = ST_GeographyFromText('SRID=4326;POINT(' || st_x(geom) || ' ' ||  st_y(geom) || ')');

with or without srid.



来源:https://stackoverflow.com/questions/2523561/how-do-i-convert-a-latitude-longitude-pair-into-a-postgis-geography-type

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