As a part of a plugin that I'm writing for a client, there's a shortcode that shows a leaflet map. The static script & css are loaded in the footer, and I can pass parameters to it via wp_localize_script.
What I need is to add a layer on mouseover event and remove it on mouseout. And as long as there is only one leaflet map per page it works. But if there is more than one map present in the same page, then the mouse events are only applied to the last map.
This is the smallest piece of javascript code that works as I said:
if (typeof map == 'undefined'){
var map = {};
var layer_bg = {};
}
map[id] = L.map(id.toString(10)).setView([51.505, -0.09], 6);
layer_bg[id] = new L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png');
map[id].on('mouseover', function(e) {
console.log(id);
map[id].addLayer( layer_bg[id] ); });
map[id].on('mouseout', function(e) {
map[id].removeLayer( layer_bg[id] ); });
The script receives a different id parameter in each call, but the events apply only to the last id used.
I'm out of ideas to solve this, but I hope there's a simple solution that I've overlooked. Here is a very simple jsfiddle that simulates 2 consecutive calls to the script above: