15

This might be a silly question, but I could not find a documented way to achieve this.

I'd like to freely position the layer-control menu, probably to the top left near the default zoom-in/out button.

My layer control looks like this:

// Group layers as overlay pane
overlayPane = {
  "Endpoints" : endpointMarkerLayer,
  "Links" : linkLineLayer
};

// Add a layer control element to the map
layerControl = L.control.layers(null, overlayPane);
layerControl.addTo(map);

Where endpointMarkerLayer and linkLineLayer are layers containing markers and polylines respectively.

Is there an option to specify where the menu should appear? Or alternatively, how can I get a reference to the DOM-objcet of the control-menu, such that I could assign it a custom class and override positioning in CSS?

2 Answers 2

19

According to the docs here, you can pass the position in as an option when creating the layer control.

Available positions are outlined here

overlayPane = {
  "Endpoints" : endpointMarkerLayer,
  "Links" : linkLineLayer,
};

// Add a layer control element to the map
layerControl = L.control.layers(null, overlayPane, {position: 'topleft'});
layerControl.addTo(map);
2
  • 1
    Wow, how did I miss that. Feeling stupid.^^
    – fgysin
    Nov 22, 2012 at 8:29
  • 1
    Feeking the same way here...
    – Stender
    Jan 20, 2020 at 10:04
6

Kelso's answer is correct. However, the documentation (and API) is a bit confusing. For example, to create a custom info box, based on this example: http://leafletjs.com/examples/choropleth.html you can do this:

var mapInfo = L.control({position:'topleft'});

info.onAdd = function (map) {
  this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info"
  this.update();
  return this._div;
};

// method that we will use to update the control based on feature properties passed
info.update = function (props) {
    this._div.innerHTML = '<h4>US Population Density</h4>' +  (props ?
    '<b>' + props.name + '</b><br />' + props.density + ' people / mi<sup>2</sup>'
    : 'Hover over a state');
};

info.addTo(map);

The options are set on the control object. So one may think you can do this to position an overlay control:

// incorrect
var layerControl = L.control({position:'topleft'}).layers(null, mapOverlays).addTo(map);

The correct way to do this, as stated above, is:

// correct
var layerControl = L.control.layers(null, mapOverlays, {position:'topleft'}).addTo(map);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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