How to get the current viewport of the map out of OpenLayers as geometry, bounding box or wkt?

Patrick Hillert picture Patrick Hillert · Jan 24, 2012 · Viewed 21.1k times · Source

I'm trying to find some hints where I should search for this topic but I've nothing found - and I spent many hours on this.

I'm also trying to get the current coordinates out of the current displayed viewport from the OpenLayers map to add only these vectors that are in the current bounding box of the current viewport.

Answer

the_skua picture the_skua · Jan 24, 2012

For OpenLayers 2:

Map.getExtent()

...will return a Bounds, which you can then use to get the lat/long coordinates in any number of ways: http://dev.openlayers.org/apidocs/files/OpenLayers/BaseTypes/Bounds-js.html#OpenLayers.Bounds

Ideally, you'd turn the vectors into Geometry objects and check them against Map.getExtent() using Bounds.intersectBounds() to see if they're in the current viewport.

For OpenLayers 3:

ol.Map.getView().calculateExtent(map.getSize())

...will return an array of coordinates, representing the bounding box of the extent.