Restrict Pan outside WMS extent in OpenLayers3

前端 未结 3 1027
无人共我
无人共我 2020-12-29 08:28

I have rectangle WMS of small area and want to restrict panning outside WMS extends, so there aren\'t white or black area outside the map visible at all. Adding exten

3条回答
  •  遥遥无期
    2020-12-29 08:59

    This is an extension to @tremby answer, but to long for a comment.

    First of all, his solution works really well for me, but it was called way to often. Therefore I wrapped it in a debounce function.

    So

    view.on('change:resolution', constrainPan);
    view.on('change:center', constrainPan);
    

    becomes

    var dConstrainPan = debounce(constrainPan);
    view.on('change:resolution', dConstrainPan);
    view.on('change:center', dConstrainPan);
    

    This will result in a slight flicker, when moving outside the bounding box, bot zooming/ moving works without delay.

    Still not perfect but a useful improvement from my point of view.

    Debounce code:

    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds. If `immediate` is passed, trigger the function on the
    // leading edge, instead of the trailing.
    function debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    };
    

    Soruce: https://davidwalsh.name/javascript-debounce-function , in underscore.js

提交回复
热议问题