Restrict Pan outside WMS extent in OpenLayers3

前端 未结 3 1024
无人共我
无人共我 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:41

    Here's a more robust implementation that should work really well in any case. It's written in ES6, and requires isEqual method (from lodash or anything else ...)

    const extent = [-357823.2365, 6037008.6939, 1313632.3628, 7230727.3772];
    const view = this.olMap.getView();
    
    const modifyValues = {};
    
    // Trick to forbid panning outside extent
    let constrainPan = (e) => {
      const type = e.type;
      const newValue = e.target.get(e.key);
      const oldValue = e.oldValue;
    
      if (isEqual(oldValue, newValue)) {
        // Do nothing when event doesn't change the value
        return;
      }
    
      if (isEqual(modifyValues[type], newValue)) {
        // Break possible infinite loop
        delete modifyValues[type];
        return;
      }
    
      if (type === 'change:resolution' && newValue < oldValue) {
        // Always allow zoom-in.
        return;
      }
    
      const visibleExtent = view.calculateExtent(this.olMap.getSize());
      const intersection = ol.extent.getIntersection(visibleExtent, extent);
      const modify = !isEqual(intersection, visibleExtent);
    
      if (modify) {
        if (type === 'change:center') {
          const newCenter = newValue.slice(0);
    
          if (ol.extent.getWidth(visibleExtent) !== ol.extent.getWidth(intersection)) {
            newCenter[0] = oldValue[0];
          }
    
          if (ol.extent.getHeight(visibleExtent) !== ol.extent.getHeight(intersection)) {
            newCenter[1] = oldValue[1];
          }
    
          modifyValues[type] = newCenter;
          view.setCenter(newCenter);
        } else if (type === 'change:resolution') {
          modifyValues[type] = oldValue;
          view.setResolution(oldValue);
        }
      }
    };
    view.on('change:resolution', constrainPan);
    view.on('change:center', constrainPan);
    

提交回复
热议问题