Can someone tell me how I can place controls outside of the map content with Leaflet?
In this case, I just want to place the layer switch control outside the map object.
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It only takes a minute to sign up.
Sign up to join this communityLeaflet does a lot of hand-waving to hide implementation of the map portal but lucky for you they have thought of a solution!
The getContainer
function is just what you need.
This returns the actual HTML node, not just the markup.
It is then just as easy as un-childing(?) the node and assign it to a new parent, with a couple lines of Javascript.
Working example and comments (and a kick-ass tileset)!
http://codepen.io/romahicks/pen/ONmPmp
The Code
//Create Layer
var baseMap = new L.TileLayer('http://{s}.tiles.mapbox.com/v3/gvenech.m13knc8e/{z}/{x}/{y}.png' );
var baseMapIndex = {
"Map": baseMap
};
// Create the map
var map = new L.map('map', {
center: new L.LatLng(41.019829, 28.989864),
zoom: 14,
maxZoom: 18,
zoomControl: false, // Disable the default zoom controls.
layers: baseMap
});
// Create the control and add it to the map;
var control = L.control.layers(baseMapIndex);
control.addTo(map);
// Call the getContainer routine.
var htmlObject = control.getContainer();
// Get the desired parent node.
var a = document.getElementById('new-parent');
// Finally append that node to the new parent, recursively searching out and re-parenting nodes.
function setParent(el, newParent)
{
newParent.appendChild(el);
}
setParent(htmlObject, a);
You must recursively go through all the children and reassign them to their parent. See the second answer for a simple recursive loop.
a.appendChild(control.onAdd(map))
should be enough. See also stackoverflow.com/questions/36041651/…
L.control.layers
.
Simple possible way i have used:
Add below html tag, where you want move the leaflet controls:
<div id="custom-map-controls"></div>
JavaScript code:
$(document).ready(function () {
var newParent = document.getElementById('custom-map-controls');
var oldParent = document.getElementsByClassName("leaflet-top leaflet-right")
while (oldParent[0].childNodes.length > 0) {
newParent.appendChild(oldParent[0].childNodes[0]);
}
});