Search code examples
postgis

PostGIS St_Contains does not return data


I have written the following example to to find if a point is within the polygon.

CREATE TABLE points_of_interest(
    id serial NOT NULL,
    name varchar(50),
    lat numeric,
    lon numeric,
    geom geometry(POINT,4326));

CREATE TABLE papakura_places(
  id serial NOT NULL,
  name varchar(50),
  lat numeric,
  lon numeric,geom geometry(POINT,4326));

insert into papakura_places(name, lat, lon) values ('a', -37.066337, 174.940995);
insert into papakura_places(name, lat, lon) values ('b',-37.067518, 174.940872);
insert into papakura_places(name, lat, lon) values ('d',-37.067334, 174.938968);
insert into papakura_places(name, lat, lon) values ('d', -37.066154, 174.939110);
insert into points_of_interest(name, lat, lon) values ('pointOfInterest', -37.066486, 174.939657);
insert into points_of_interest(name, lat, lon) values ('noPointOfInterest', -37.061010, 174.943166);

UPDATE papakura_places SET geom = ST_SetSRID(ST_MakePoint(lon,lat),4326);
UPDATE points_of_interest SET geom = ST_SetSRID(ST_MakePoint(lon,lat),4326);

select * from papakura_places;
select * from points_of_interest where name like 'pointOfInterest';

select distinct * from papakura_places,points_of_interest ;

SELECT points_of_interest.*
FROM  points_of_interest, papakura_places
WHERE ST_intersects(points_of_interest.geom, papakura_places.geom);

I have verified the two points on the google maps. one is inside and one is outside. So the result should return something. But not sure why its not returning.


Solution

  • The papakura_places table has point geom. ST_Contains will not return true when points of interest lie within the four points in the table.

    Instead, make a polygon with the papakura_places points, and use that with ST_Contains:

    WITH papakura_places_polygon AS (
        SELECT
            ST_MakePolygon(ST_MakeLine(geom)) AS geom
        FROM
            ((select * from papakura_places) union all (select * from papakura_places limit 1)) a
    )
    SELECT
        *
    FROM
        points_of_interest poi
        JOIN
        papakura_places_polygon ppp ON ST_Contains(ppp.geom, poi.geom);