I would appreciate a little help. Right now I'm learning Openlayers 3. I want to bind a click event to several map objects within a for loop.
When I do it like this, the event is only applied to the last map object within the for loop:
for(var i = 0; i < $('.easymap').length;i++) {
// [...]
var elem = map[i];
elem.on('singleclick',function(evt){
elem.getView().setCenter(evt.coordinate);
});
}
I think I already found out that this a typical problem where a "closure" is needed. However, I didn't find out how to do this yet.
The following (stupid) workaround, which works only for a given number of maps and produces many lines of redundant code, is only a temporary solution:
// solve later (make dynamic, learn how to use closures... )
if($('#easymap1').length && $('#easymap1').hasClass('addpost')) map[0].on('singleclick',function(evt){ /*alert(ol.coordinate.format(evt.coordinate, '{x}')+' '+ol.coordinate.format(evt.coordinate, '{y}'));*/ map[0].getView().setCenter(evt.coordinate); });
if($('#easymap2').length && $('#easymap2').hasClass('addpost')) map[1].on('singleclick',function(evt){ map[1].getView().setCenter(evt.coordinate); });
if($('#easymap3').length && $('#easymap3').hasClass('addpost')) map[2].on('singleclick',function(evt){ map[2].getView().setCenter(evt.coordinate); });
if($('#easymap4').length && $('#easymap4').hasClass('addpost')) map[3].on('singleclick',function(evt){ map[3].getView().setCenter(evt.coordinate); });
if($('#easymap5').length && $('#easymap5').hasClass('addpost')) map[4].on('singleclick',function(evt){ map[4].getView().setCenter(evt.coordinate); });
So, does can anyone tell my how to integrate this into a proper for loop? Thank you.
Best regards joschi81