2

I have been using Leaflet.js but since I wanted the webgl performance I switched to the newly OpenLayers 3 which seems awesome.

I had bounds on my Leaflet.js Map:

var sw = L.latLng(-90, 180),
    ne = L.latLng(90, -180),
    maxBounds = L.latLngBounds(sw, ne);

map = new L.Map('map', {            
        attribution: "",
        attributionControl: false,
        maxBounds: maxBounds,
        zoomControl: false,
        zoomAnimation: true
    }
);

where I only had a single projection being allowed to be displayed and if the user would attempt to go out of bounds, the map would bounce back with an animation.

Is there a way to have something similar with OpenLayers 3?

I basically want to prevent dragging or changing center beyond the actual bounds of a single projection.

I used the following code with OpenLayers 3:

map.on('postrender', function () {
    var view = map.getView(),
        worldExtent = view.getProjection().getExtent(),
        extent = view.calculateExtent(map.getSize());

    if (!ol.extent.containsExtent(worldExtent, extent)) {
        var newExtent = ol.extent.getIntersection(extent, restrictedExtent);
        view.fit(newExtent, map.getSize());
    }
});

which displays a signle projection all right but I can drag or move the center out of it.

  • 1
    I would explore attaching an event listener..for a 'moveend' and then call a custom function that does the quick check and if it's bad, issue a pan to the nearest legal spot. see example: openlayers.org/en/v3.1.1/examples/moveend.html – user1269942 Nov 3 '15 at 17:57
  • this is what i had in mind actually but i wnated to know if OL3 had something out of the box – DaTroop Nov 4 '15 at 13:01
0

You can set the extent when initialising your view. Within docs (link) it sais:

The extent that constrains the center, in other words, center cannot be set outside this extent. Default is undefined.

consider this

var map = new ol.Map({
  layers: layers,
  target: 'map',
  view: new ol.View({
    center: [-6655.5402445057125, 6709968.258934638],
    extent:[-16655.5402445057125, 6609968.258934638,0,6809968],
    zoom: 13
  })
});

You have to consider also the zoom levels available. If a high zoom level is available then your map will be displayed ouside the supplied extend but your map center wont go over the supplied extent. Here is a fiddle to test.

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.