BKR
BKR

Reputation: 443

OpenLayers 3: Sync/Unsync Different Maps Events

Let's say I have N different maps on the screen, I want to be able based on a condition, let s say a value coming from a checkbox or a different control to be able to sync all the map events (zoom/pan/rotation) and unsync them accordingly. Can this be achieved in OpenLayers 3 using native code?

Upvotes: 0

Views: 825

Answers (2)

blindfish
blindfish

Reputation: 843

I'm working on a project with fairly heavy WMS layers and hit a problem with Alvin's solution. For the first map OL waits for any interaction to end before requesting an updated WMS layer. But for the second map it appears to treat each step triggered by the function as a separate interaction and therefore generates a separate WMS layer request at each step. In my case this was seriously affecting performance.

I've come up with a compromise solution that waits for interaction to end and then animates the second map to match the first. This is a first attempt and could probably be improved:

// attributes to synchronise between maps
var synchedAttributes = ['resolution', 'center']

// call this on moveend
var syncPanZoom = function(maps, evt){

  maps.forEach(function(map){

    synchedAttributes.forEach(function(attribute) {

      var value = evt.target.getView().get(attribute);

      if (map.olmap.getView().get(attribute) !== value){
        var animateObject = {};
        animateObject[attribute] = value;
        animateObject.duration = 500;
        map.olmap.getView().animate(animateObject)
      }

    });

  });

};

Upvotes: 0

Alvin Lindstam
Alvin Lindstam

Reputation: 3142

You can sync maps by listen to their events and setting their changes to the other maps. I wrote a working example, using this as the listener for each map's view's change:center, change:resolution and change:rotation event:

function(evt){
    var type = evt.type.split(':');
    if (type[0] === 'change' && type.length === 2){
        var attribute = type[1];
        maps.forEach(function(map){
            var value = evt.target.get(attribute);
            if (map.getView().get(attribute) !== value){
                map.getView().set(attribute, value);
            }
        });
    }
}

Upvotes: 2

Related Questions