title: Legends on R Leaflet Maps
body: <p>While I realize that putting legends on maps using the Rstudio <a href="https://rstudio.github.io/leaflet/" rel="nofollow"><code>leaflet</code> package</a> is still a work in progress, I've been trying to add a legend <em>post-hoc</em> to the HTML that R generates.</p>
  
  <pre><code>library("leaflet")
  set.seed(100)
  pdf &lt;- data.frame(Latitude = runif(100, -90,90), Longitude = runif(100, -180,180), 
                    col=rep(c("red", "blue"), 50 ))
  
  #just red
  leaflet(pdf) %&gt;% addTiles()  %&gt;%
    addCircleMarkers(lat = ~ Latitude, lng = ~ Longitude, color= ~col)
  </code></pre>
  
  <p>I've been trying to adapt the code from <a href="http://leafletjs.com/examples/choropleth.html" rel="nofollow">http://leafletjs.com/examples/choropleth.html</a> and figure out where to add it to the output from running the above code in R and turning it into HTML.</p>
  
  <p>So something like putting the following in the body of the html:</p>
  
  <pre><code>&lt;script&gt;
  var legend = L.control({position: 'bottomright'});
  
  legend.onAdd = function (map) {
  
      var div = L.DomUtil.create('div', 'info legend'),
          grades = [red, blue],
          labels = [];
  
      // loop through our density intervals and generate a label with a colored square for each label
      for (var i = 0; i &lt; grades.length; i++) {
          div.innerHTML +=
              '&lt;i style="background:' + getColor(grades[i] + 1) + '"&gt;&lt;/i&gt; ' +
              grades[i] + (grades[i + 1] ? '&amp;ndash;' + grades[i + 1] + '&lt;br&gt;' : '+');
      }
  
      return div;
  };
  
  legend.addTo(map);
  &lt;script&gt;
  </code></pre>
  
  <p>This doesn't seem to work, however. Nothing pops up. Nor is it clear how I would use names other than 'red', and 'blue' for the grades, as it were. I've also added in CSS as shown in the choropleth example as well, but no dice.</p>
  
  <p>Has anyone done this - manually added a legend to their R output (say, grabbing the source from Rpubs after publishing) to add a legend?</p>