6

I am building a web application where I need to compare 2 different maps of the same area, I need for the events on one map to automatically be triggered on the other map. I have so far: map2.events.triggerEvent(evt.type,evt.px);

There is a map compare at http://tools.geofabrik.de/mc/?lon=29.53125&lat=22.26877&zoom=2 but I have no idea how they achieved this event handling.

2 Answers 2

7

If you need to synchronize only moving and zooming of map, one simple solution is: listen moveend event on map, and then zoom other map to extent of current map.

map1 = new OpenLayers.Map('map1');
map2 = new OpenLayers.Map('map2');

map1.events.on({
    moveend: function(evt) {
        map2.zoomToExtent(map1.getExtent());
        
    }       
});

map2.events.on({
    moveend: function(evt) {
        map1.zoomToExtent(map2.getExtent());
    }       
});    

Here's fiddle: http://jsfiddle.net/LwPEd/2/

I was afraid at first, that there will be an infinite loop when zoomToExtent triggers new event, but it works.

0
4

It's also possible to make the feedback instant, at the cost of complicating the code a bit (and causing potential performance problems if there are other events attached to the maps):

I used @user1702401's answer and their Fiddle as a template.

var mapFollow = function(mapA, mapB) {
    var syncMapHandler = function() {
        var aCenter = mapA.getCenter();
        var bCenter = mapB.getCenter();

        var coordsChanged = ((aCenter.lat !== bCenter.lat) ||
            (aCenter.lon !== bCenter.lon));

        if (coordsChanged) {
            mapB.moveTo(mapA.getCenter(), mapA.getZoom(), {
                dragging: true
            });
        }
    };

    mapA.events.on({
        'move': syncMapHandler,
        'zoomend': syncMapHandler,
        scope: this
    });
};

map1 = new OpenLayers.Map('map1');
map2 = new OpenLayers.Map('map2');

mapFollow(map1, map2);
mapFollow(map2, map1);

Live example here: http://jsfiddle.net/4Wf7W/5/

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.