0

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:

http://jsfiddle.net/LTYvq/1/

joseLuís
  • 1,090
  • 9
  • 10

1 Answers1

0

It is a scope problem.

id is a global variable, so everytime you call console.log(id); it will use the global id, which was last set to "map2".

To fix it, put the creation code into a function like so:

function createMap(id) {

   if (typeof map == 'undefined'){
    map = {};
    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] ); });   
}

and then call

createMap("map1");
createMap("map2");

For more about scopes, see What is the scope of variables in JavaScript?

I updated you Fiddle here: http://jsfiddle.net/LTYvq/3/

Community
  • 1
  • 1
Robert Dodd
  • 2,148
  • 2
  • 21
  • 28