Skip to content
Advertisement

PostgreSQL: show trips within a bounding box

I have a trips table containing user’s trip information, like so:

The task is to filter trips that start and end within the bounding box defined by upper left: 41.24895, -8.68494 and lower right: 41.11591, -8.47569.

Advertisement

Answer

Since your coordinates are stored in x,y columns, you have to use ST_MakePoint to create a proper geometry. After that, you can create a BBOX using the function ST_MakeEnvelope and check if start and end coordinates are inside the BBOX using ST_Contains, e.g.

Note: the CTE isn’t really necessary and is in the query just for illustration purposes. You can repeat the ST_MakeEnvelope function on both conditions in the WHERE clause instead of bbox.geom. This query also assumes the SRS WGS84 (4326).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement