I've started digging deep into PostgreSQL and PostGIS for a very geo centric project I'm working on.
PostGIS is an extension that provides geo spatial functionality to PostgreSQL.
Let's say you have a table of neighborhoods, where each record contains an id and a list of coordinates that make up the boundary of each neighborhood.
The following query would return the id of the neighborhood the coordinates -117.289 33.949 exists within.
SELECT id FROM neighborhoods
WHERE ST_Contains(neighborhoods.geometry,
ST_Transform(
ST_GeomFromText('POINT(-117.289 33.949)', 4326), 4326
)
)
That's pretty verbose, so let's make a database function for it.
create or replace function in_neighborhood(coords varchar(255))
returns varchar(255)
as $$
declare
myid varchar(255);
begin
SELECT id FROM zones
WHERE ST_Contains(zones.geometry, ST_Transform(
ST_GeomFromText(concat('POINT(', coords, ')'), 4326), 4326)
)
into myid;
return myid;
end;
$$
language plpgsql;
Now we can achieve the same result as our original query by running the following SQL:
select in_neighborhood('-117.289 33.949');