title: Leaflet .addLayer() fails in function, works at the console
body: <p>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 <a href="https://github.com/GeoSprocket/sactree-map/blob/master/layers.js#L42-L53" rel="nofollow">using a click function</a>. Specifically, I have a leaflet map with numerous vector layers defined. One of these layers is added to the map <a href="https://github.com/GeoSprocket/sactree-map/blob/master/layers.js#L128" rel="nofollow">on page load</a>, and then subsequent layers are supposed to load on a click event in a layer selector.</p>
  
  <p>Here's the function that handles the click, then updates the sidebar legend, updates classes in the layer selector, and <strong>is supposed to</strong> update the visible layer:</p>
  
  <pre><code>// ADD THE LAYER CONTROL FUNCTION
  $('.layer').click(function() {
    var oldLayer = $('.active').attr('id');
    var newLayer = $(this).attr('id');
    console.log(oldLayer + ' --&gt; ' + newLayer);
    $('#infobits').html('&lt;h2&gt;' + this.text + '&lt;/h2&gt;&lt;hr&gt;' + legendFormatter(
      this.id));
    map.removeLayer(oldLayer);
    $('.layer').removeClass('active');
    $(this).addClass('active');
    map.addLayer(newLayer);
  });
  </code></pre>
  
  <p>Every time I click on a new layer I get <code>Uncaught TypeError: undefined is not a function</code>, 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 <strong>verbatim</strong> what the function is producing on line 49 of the above script (<code>map.removeLayer(Percent_TC_bg)</code>), the map removes the layer in question.</p>
  
  <p>What can I do to get my map adding and removing layers without error?</p>