5

I am working on OpenLayers (ol3) and I want to get the Latitude, Longitude of the corners of the map being shown at a point. I tried using map.getView().getProjection().getExtent() and converting the points from 'EPSG:3857' to 'EPSG:4326' but I get -180,-85.05112877980659,180,85.05112877980659 irrespective of the zoom level of the map I have set.

I would like to know the map view corner points dynamically.

4

You can get the current extent with:

var extent = map.getView().calculateExtent(map.getSize());

Then you can use ol.proj.transformExtent to reproject the extent.

4

The available answers didn't work easily so I'm pasting my solution:

var glbox = map.getView().calculateExtent(map.getSize()); // doesn't look as expected.
var box = ol.proj.transformExtent(glbox,'EPSG:3857','EPSG:4326'); // this looked like what I expected.
1

It looks like you are retrieving the extent of the projection, and not the current map.

You could try getExtent:

map.getExtent();

This returns a bounds object that can be transformed to give lat lon.

  • 1
    This is for OpenLayers 2, for OpenLayers 3 use map.getView().calculateExtent(map.getSize()). – tsauerwein Feb 12 '15 at 17:01
1

I'm guessing you mean the extent of the View at any zoom or center.
Btw I have all my layers in 4326 so no convertion need it.

I use this to avoid pan the map outside an area.
If you know map.size (that is html div size) and resolution (that depend on zoom) you can know how big is your Extent.
Then using your center you can calculate all corners.

var maxExtent = [-79.59975, -1.200, -53.03076, 13.72883];
view.on('change:center', function (evt) {
    var center = view.getCenter();
    var x = center[0];
    var y = center[1];
    var resolution = view.getResolution();
    var mapSize = map.getSize();

    var mapHalfWidth = (mapSize[0] * resolution) / 2.0;
    var mapHalfHeight = (mapSize[1] * resolution) / 2.0;

    if (center[0] - mapHalfWidth < maxExtent[0]) {
        x = maxExtent[0] + mapHalfWidth;
    } else if (center[0] + mapHalfWidth > maxExtent[2]) {
        x = maxExtent[2] - mapHalfWidth;
    }
    if (center[1] - mapHalfHeight < maxExtent[1]) {
        y = maxExtent[1] + mapHalfHeight;
    } else if (center[1] + mapHalfHeight > maxExtent[3]) {
        y = maxExtent[3] - mapHalfHeight;
    }

    if (center[0] != x || center[1] != y) {
        view.setCenter([x, y]);
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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