1

I am using mapbox.js 1.6.1 to serve .mbtiles created in tilemill (via mbtiles-server.php) on a private host.

my knowledge of html and js is very (very) basic, I can't figure out how to use L.mapbox.legendControl properly to add a legend to a L.mapbox.map map.

I am using mbtiles-server.php to serve .mbtiles created in tilemill. Here is what works:

//create map, centered on papua
  var map = L.mapbox.map('map', 'server/mal.tilejson').setView([-6, 140], 6);

this creates a map with the tile- and gridlayer (hover tooltips) as well as the legend.

I have not been successful with creating an empty map and adding layers with their legends showing:

//create map, centered on papua
  var map = L.mapbox.map('map').setView([-6, 140], 6);

//baselayer
  var srtm = L.mapbox.tileLayer('server/neuguinea_zl3-14.tilejson', {
                        maxZoom: 14,
                }).addTo(map);

//overlay
 var malgroup = new L.LayerGroup();
 var malariatile = L.mapbox.tileLayer('server/mal.tilejson').addTo(malgroup);
 var malariagrid = L.mapbox.gridLayer('server/mal.tilejson').addTo(malgroup); 
 map.addControl(L.mapbox.gridControl(malariagrid));

//create baselayers and overlays
var baseLayers = {
  "SRTM v3": srtm
  };
var overlay = {
  "Malaria": malgroup
  };

//add layer control
 L.control.layers(baseLayers, overlay).addTo(map);

// create legend
  map.addControl(L.mapbox.legendControl());

I was hoping that map.addControl(L.mapbox.legendControl()); would activate the overlay's legend automatically, but it doesn't.

Thanks for looking into this!

1

I believe your line map.addControl(L.mapbox.legendControl()); needs to be written as: map.legendControl.addLegend(legend); If you look at the json data parsed by your url string 'server/neuguinea_zl3-14.tilejson' (plug the url into your browser's address bar) you should see that 'legend' is one of the array elements that gets parsed.

Also check your browser's debugger (firebug) for any javascript errors. You'll never fix javascript errors without checking the debugger.

Alternately you could try creating your own custom legend right on your html page. To insert it into your map use something like:

<div id='my-legend' style='display: none;'>
  <div> legend content... </div>
</div>

<script>
  var map = L.mapbox.map('map');
    ...
  map.legendControl.addLegend(document.getElementById('my-legend').innerHTML);
</script>

Where 'my-legend' is the id of the element that contains your legend's html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.