2

I have a db structure that is vanilla Postgres:

CREATE TABLE IF NOT EXISTS locations (
  name text NOT NULL,
  lat double precision NOT NULL,
  lng double precision NOT NULL,
);
CREATE INDEX ON locations(lat,lng);

When I want to calculate all locations in a bounding box where I have the lower left and upper right corners I use the following query:

SELECT * FROM locations 
WHERE lat >= min_lat AND
WHERE lat <= max_lat AND
WHERE lng >= min_lng AND
WHERE lng <= max_lng; 

Now, I want to generate a bounding box given a point and use the bounding box result in the locations query. I'm using the following PostGIS query to generate a bounding box:

SELECT 
  ST_Extent(
   ST_Envelope(
    ST_Rotate(
     ST_Buffer(
      ST_GeomFromText('POINT (-87.6297982 41.8781136)',4326)::GEOGRAPHY,160934)::GEOMETRY,0)));

Result: BOX(-89.568160053866 40.4285062983089,-85.6903925527536 43.3273499289221)

However, I'm not sure how use the results from the PostGIS query bounding box into the vanilla lat / lng Postgres query in one call. Any ideas on how to merge the two? Preferably such that the index is preserved.

zup_zup
  • 87
  • 8

1 Answers1

3

If you want to get the bbox coordinates as separated values you might wanna take a look at ST_XMax, ST_YMax, ST_XMin, ST_YMin. The following CTE, that embeds your query, should give you an idea:

WITH j (geom) AS (
 SELECT 
  ST_Extent(ST_Envelope(
   ST_Rotate(ST_Buffer(
    ST_GeomFromText('POINT(-87.6297982 41.8781136)',4326)::GEOGRAPHY,160934)::GEOMETRY,0)))
)
SELECT
    ST_XMax(geom),ST_YMax(geom),
    ST_XMin(geom),ST_YMin(geom)
FROM j


      st_xmax      |     st_ymax     |      st_xmin      |     st_ymin      
-------------------+-----------------+-------------------+------------------
 -85.6903925527536 | 43.327349928921 | -89.5681600538661 | 40.4285062983098

Side note: Storing geometry values as numbers might look straightforward but it is hardly ever the better choice - specially when dealing with polygons! So I would really suggest you to store these values as geometry or geography, which might seem complex at first a glance but definitely pays off on the long run.

This answer might shed a light on distance/containment queries involving polygons: Getting all Buildings in range of 5 miles from specified coordinates

Jim Jones
  • 18,404
  • 3
  • 35
  • 44