I have 2 tables User_places where I can see for each user their home location defined by 2 separate attributes: longitude and latitude. And I have second table Neighborhoods with attribute 'Area', that defines each neighborhood as polygon - jsonb format - "[{"latitude":XXXXX,"longitude":YYYYY},{"latitude":ZZZZZ,"longitude":AAAAA},{"latitude":BBBBBB,"longitude":CCCCC},{"latitude":DDDDD,"longitude":EEEEE}]".
Does anybody know how to check whether particular user lives in given neighborhood in Postgresql?
SELECT
user_id,
ST_Contains(
ST_GeomFromText(
(select
replace(replace(replace(replace(replace(area::text,']','))'),'[','POLYGON(('),'}', ''),',"longitude":',' '),'{"latitude":','')
from neighbourhoods
limit 1), 4326)
(ST_SetSRID(ST_MakePoint(latitude, longitude),4326))
) as polygon_check
from user_places
I will assume you have Postgis installed on your copy of postgresql? As this has all the Geometry and geographical function extensions to postgresql.
You could use ST_Contains to check if a point is contained in a given polygon, this returns a boolean.
select ST_Contains(neigbourhood.polygon,User_place.geom)
If you don't have a geom point value in the User_places table then this can be created using the ST_SetSRID function and ST_MakePoint function.
For example - SELECT ST_SetSRID(ST_MakePoint(LAT, LON),SRID);
where SRID is the reference for the projection you are using for example 4326 for WGS 84 `
I would recommend in postgresql make sure all of your Geographical tables have geoms in them, as it makes comparisons much easier.
For reference a good place to get answers for geographic and geometry database based questions is https://gis.stackexchange.com/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.