0

I want to simply center my map on the search result of a polygon using leaflet. I thought to return the bounding box, as this is closer to what I actually need.

I want to use flyTo()

I see a possible way to do this by using Leaflet?

I have a thought to do this

SELECT ST_AsGeoJSON (geom) AS geom, Box2D(geom) as bounds, ST_YMax(Box2D(geom)) as ymax, ST_YMin(Box2D(geom)) as ymin, ST_XMax(Box2D(geom)) as xmax, ST_XMin(Box2D(geom)) as xmin FROM nation_shapes WHERE (condition)

and then pass it to

mymap.flyToBounds([[ymax, xmax],[ymin, xmin]])

Though this seems inefficient. I would like to be able to get this information from the object I am already passing back if possible, or convert something like Box2D(geom) as bounds which would be more efficient than calling it 4 times, I think.

3
  • Is this Leaflet or PostgreSQL question? Leaflet flyTo method takes as argument single lat,lng point, flyToBounds method takes bounding box as argument.
    – TomazicM
    Aug 29, 2019 at 19:27
  • @TomazicM thanks, fixed. It's both because I am storing the data in PostgreSQL / PostGIS and displaying with leaflet. I am searching for a way to display a BOX type in leaflet, if possible. I have it working now with the way I mention first.
    – Douglas
    Aug 29, 2019 at 20:01
  • This is then PostgreSQL / PostGIS question which is beyond my knowledge.
    – TomazicM
    Aug 29, 2019 at 20:40

1 Answer 1

2

I would go with...

SELECT Box2D(geom) as bounds, 
    ST_YMax(bounds) as ymax,
    ST_YMin(bounds) as ymin,
    ST_XMax(bounds) as xmax,
    ST_XMin(bounds) as xmin
    FROM nation_shapes WHERE (condition)

...as PostgreSQL's SQL engine and query planner is smart enough to figure things out and not duplicate work.

If you want to not return the bbox from the query, then

SELECT ymax, ymin, xmax, xmin FROM (
  SELECT Box2D(geom) as bounds, 
    ST_YMax(bounds) as ymax,
    ST_YMin(bounds) as ymin,
    ST_XMax(bounds) as xmax,
    ST_XMin(bounds) as xmin
    FROM nation_shapes WHERE (condition)
  )

which would be more efficient than calling it 4 times, I think.

Beware of premature optimization. Do not assume efficiency in SQL queries unless you take some time to EXPLAIN the query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.