Search code examples
postgresqlpostgis

postgis How do I find results within a given bounding box that are close to the center?


I'm learning postgis and saw that there is ST_MakeEnvelope to which I can pass my bounding box coordinates:

ST_MakeEnvelope(${params.swLng},${params.swLat},${params.neLng},${params.neLat}, 4326)

However, is there a way to get the results that are closest to the center of the bounding box? Is it possible to combine the bounding box with a radius query?


Solution

  • You can order by distance between your geometries and the centroid of the envelope

    SELECT *
    FROM myTable
    WHERE st_intersects(geom, ST_makeEnvelope(...))
    ORDER BY geom <-> st_centroid(ST_makeEnvelope(...))