Reputation: 36058
I create two openlayer maps in my page, now I want them work synchronized.
For example, one map's center or zoom is changed, then another have change its accordingly.
And vice versa.
Which event should I registed to the map?
Upvotes: 2
Views: 1052
Reputation: 11
This is indeed possible, as I have just done it. You need to trap the 'moveend' and 'move' events from the map being panned or zoomed (moveend is triggered at the end of a zoom, but you could trap 'zoomend' as well to be on the safe side). If you trap these using the parent map as the context then you can get the new map centre. Bear in mind that the map centre can change when the map is zoomed if the navigation control is being used and the zoom is done using the mouse. Then use the moveTo method (childmap.moveTo().
I've chosen the moveTo method as (although not well documented) this is what is always finally called in any pan or zoom event on any map. As an aside, calling moveTo will also cause the 'move', 'moveend' events to be triggered on the child map.
If you make a collection of maps using json, and use jQuery, the actual code would look something like this (I'm assuming you know how to trap map events in OpenLayers);
var newCentre = zoomedMap.getCenter();
$.each(maps, function (ind, map) {
if (map !== zoomedMap) map.moveTo(newCentre, newZoom);
});
where maps is my collection of maps, zoomedMap is the map the user actually triggered the pan or zoom event on (I've called it zoomeMap but it could just as easily be called pannedMap), and (obviously) map is the map in the collection that needs moving.
I played around a bit before I settled for the above code. The advantage here is that $.each doesn't wait for the moveTo function to return, so you get a much slicker looking synch. Of course this wouldn't really be an issue if you're only synching two maps.
I'm sorry to have posted this so long after the question was asked, but maybe it will help any new searchers out there.
Upvotes: 1