[GIS] Placing controls outside map container with Leaflet

leaflet

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.

enter image description here

Best Answer

Leaflet 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.

https://stackoverflow.com/questions/20910147/how-to-move-all-html-element-children-to-another-parent-using-javascript