Search code examples
sqlpostgresqlpostgis

Check whether the point (latitude and longitude) on the map inside the polygon


Earlier, I used function to find whether a point on a map is in a radius. But the conditions have changed and I need to check the entry point in the polygon. I have at least four points - northeast / southeast / southwest / northwest with latitude and longitude. But it looks like ST_GeogFromText('POLYGON(())') designed for completely different things or I can't figure out how to use them.

My example for distance:

create table "Locations"
(
  id serial not null constraint "Locations_pkey" primary key,
  name varchar(120),
  geopin geometry(Point, 4326)
);

select *
from "Locations"
where
  ST_DWithin(
    "Locations"."geopin",
    ST_MakePoint(90.00, 90.00)::geography,
    10000
  );

What i can't figure out.

select *
from "Locations"
where
  SOME_FUNCTION_TO_SEARCH_IN_POLYGON(
  "Locations"."geopin",
    SOME_GEOGRAPHY_FROM_POLYGON(0 0,0 180,180 0,180 180)
  );

Even better if there will be enough to provide only NE and SW latitude and longitude.


Solution

  • You would do a spatial intersection. Since you are not computing distances anymore, you can do the comparison using the geometries in 4326 directly, no need to cast to Geography.

    To build the polygon with its corner coordinates, you can build a 2D box

    WITH src AS (select St_GeomFromText('Point(25 25)',4326) as geopin),
        searchArea AS (select ST_SETSRID(
                ST_MakeBox2D(
                    ST_MakePoint(-170, -75),
                    ST_MakePoint(170, 45)),
            4326) as geom)
    SELECT ST_Intersects(geopin,geom)
    FROM src, searchArea;