Search code examples
openlayersopenlayers-5

OL Mapview: provided boundaries are not used........why?


When I supply the leftbottom and righttop coordinates for mapview these are not exactly used. The resulting difference is pretty big. What am I missing?!

Bounds = [-0.6688232421875, 49.78322566351028, 11.6688232421875, 54.35032343193191];
Bounds = ol.proj.transformExtent(Bounds, ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));


var map = new ol.Map({
    target: 'map',
    view: new ol.View({
        projection: "EPSG:3857"
        })
    });

map.getView().fit(Bounds,map.getSize());

The mapview gets new ('larger') bounds, but not the above ones. The 'new' bounds are [-6.837646484374999,47.32226629045806,17.837646484375,56.461134011735425]

How can I get the map to stick to the provided ones??

EDIT: I have adjusted the code based on comments from Mike (thx!!). ** What is the best way to achieve what I want......i.e. display part of the map that is within a boundingbox that has the above leftbottom and righttop (LON/LAT) coordinates? **


Solution

  • The bounds are being used but unless you specify constrainResolution: false the view will snap to the closest integer zoom level. This code demonstrates getting an exact fit by allowing a fractional zoom level. Note that if the map width/height ratio doesn't match the extent there will be some excess coverage

    Bounds = [-0.6688232421875, 49.78322566351028, 11.6688232421875, 54.35032343193191];
    Bounds = ol.proj.transformExtent(Bounds, ol.proj.get('EPSG:4326'), ol.proj.get('EPSG:3857'));
    
    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }),
            new ol.layer.Vector({
                source: new ol.source.Vector({
                    features: [new ol.Feature(ol.geom.Polygon.fromExtent(Bounds))]
                })
            })
        ]
    });
    map.getView().fit(Bounds, {size: map.getSize(), constrainResolution: false});