20

I have a minLat, minLong, maxLat and maxLong from a box drawn on a map. Right now, my query to get all the points in the box looks like this:

SELECT *
FROM geomTable
WHERE (longitude BETWEEN minLon AND maxLon)
AND (latitude BETWEEN minLat AND maxLat)

I want to use the geometry column instead of lat/long columns to get the results. I tried this query:

SELECT *
FROM mytable
WHERE mytable.geom && ST_MakeEnvelope(minLon, minLat, maxLon, maxLat, 4326);

from this post: Select bounding box using postgis but it is returning no results.

Does anyone have an example of how to select all the points within a box created by min and max lat/longs using geometry in postgis?

bl8rchk
  • 551
  • 1
  • 3
  • 14

1 Answers1

20

Your data is not in lat/lon, so you need to push your box into the coordinate space of your data:

SELECT *
FROM mytable
WHERE 
  mytable.geom && 
  ST_Transform(ST_MakeEnvelope(minLon, minLat, maxLon, maxLat, 4326), 2223);
Paul Ramsey
  • 19,865
  • 1
  • 47
  • 57