Search code examples
postgresqlpostgisgeojson

Search a point exists on which polygon row?


I have inserted multiple location rows with geojson value on a geometry column and trying to search it based on a point value, I need to find the point is exists on the polygon or not? I've seen this https://stackoverflow.com/a/38941705/1138192 but I have geojson value to insert and search by point.

What I have tried So far:

CREATE TABLE areas (
    id SERIAL PRIMARY KEY,
    name VARCHAR(64),
    the_geom GEOMETRY
);

CREATE INDEX areas_the_geom_idx ON areas USING GIST (the_geom);

INSERT INTO areas (name, the_geom)
    VALUES ('Corrected_Shape', 
    ST_TRANSFORM(ST_GeomFromGeoJSON('{
    "type":"Polygon",
    "coordinates":[[
        [-91.23046875,45.460130637921],
        [-79.8046875,49.837982453085],
        [-69.08203125,43.452918893555],
        [-88.2421875,32.694865977875],
        [-91.23046875,45.460130637921]
    ]],
    "crs":{"type":"name","properties":{"name":"EPSG:4326"}}
}'),3857));

SELECT name FROM areas WHERE ST_Contains(the_geom, ST_GeomFromText('POINT(43.452918 -69.082031)'));

enter image description here


Solution

  • First, it seems you have swapped longitude and latitude when creating the point (it should be longitude first)

    --> ST_GeomFromText('POINT(-69.082031 43.452918)')

    Then, you have projected the polygon geometry to 3857 but not the point. You must use the same CRS for both geometries.

    --> ST_TRANSFORM(ST_GeomFromText('POINT(-69.082031 43.452918)'),3857)