Bill Morris
Bill Morris

Reputation: 599

Leaflet .addLayer() fails in function, works at the console

I think this means I'm missing something basic about the working of nested functions in javascript, but I'm failing to add or remove a layer from a leaflet map using a click function. Specifically, I have a leaflet map with numerous vector layers defined. One of these layers is added to the map on page load, and then subsequent layers are supposed to load on a click event in a layer selector.

Here's the function that handles the click, then updates the sidebar legend, updates classes in the layer selector, and is supposed to update the visible layer:

// ADD THE LAYER CONTROL FUNCTION
$('.layer').click(function() {
  var oldLayer = $('.active').attr('id');
  var newLayer = $(this).attr('id');
  console.log(oldLayer + ' --> ' + newLayer);
  $('#infobits').html('<h2>' + this.text + '</h2><hr>' + legendFormatter(
    this.id));
  map.removeLayer(oldLayer);
  $('.layer').removeClass('active');
  $(this).addClass('active');
  map.addLayer(newLayer);
});

Every time I click on a new layer I get Uncaught TypeError: undefined is not a function, no matter where I put the function (I even had it inside the .getJSON() call for a bit). What's perplexing is that is I go to the JS console in my browser and type verbatim what the function is producing on line 49 of the above script (map.removeLayer(Percent_TC_bg)), the map removes the layer in question.

What can I do to get my map adding and removing layers without error?

Upvotes: 3

Views: 9836

Answers (2)

jczaplew
jczaplew

Reputation: 1753

Edit: Igor beat me to it.

Mics is right - the HTML element's ID is a string, and doesn't reference the layer. You could do something like this after you define your layers to work around this issue:

var myLayers = {
    "Percent_TC_bg": Percent_TC_bg,
    "Percent_TC": Percent_TC
};

And then add the handler like so

$('.layer').click(function() {
  var oldLayer = myLayers[$('.active').attr('id')];
  var newLayer = myLayers[$(this).attr('id')];
  // ...
});

Upvotes: 2

Mics
Mics

Reputation: 1430

I suppose TypeError is thrown inside addLayer or removeLayer. Map#addLayer and #removeLayer accepts ILayer object as parameter, but oldLayer and newLayer is obviously String, which came directly from HTML element's ID property.

So changing oldLayer and newLayer to appreciate ILayer object will fix the problem, I guess.

Upvotes: 5

Related Questions