Skip to content

Instantly share code, notes, and snippets.

@jeffreymorganio
Last active June 18, 2016 09:02
Show Gist options
  • Save jeffreymorganio/244d7a38924751a088cb5c7c2e4b9aff to your computer and use it in GitHub Desktop.
Save jeffreymorganio/244d7a38924751a088cb5c7c2e4b9aff to your computer and use it in GitHub Desktop.
Toggling LeafletJS Layer Groups with Custom Controls.
license: mit
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css" />
<link rel="stylesheet" href="map.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js"></script>
<script src="map.js"></script>
<title>Toggling LeafletJS Layer Groups with Custom Controls</title>
</head>
<body onload="showMap()">
<div id="container">
<form id="controls">
<label><input type="checkbox" checked="checked" onclick="toggleLayer('Layer 1')">Layer 1</label>
<label><input type="checkbox" checked="checked" onclick="toggleLayer('Layer 2')">Layer 2</label>
</form>
<div id="leaflet-map"></div>
</div>
</body>
</html>
#container {
width: 962px;
height: 502px;
}
#controls {
height: 25px;
margin: 10px;
font-family: sans-serif;
}
#leaflet-map {
width: 100%;
height: 457px;
}
var map = null;
var zoomLevel = 13;
var paris = new L.LatLng(48.874652, 2.3200449);
var layers = null;
function showMap() {
initMap();
createLayers();
addLayers();
}
function initMap() {
var tileLayer = createTileLayer();
var mapOptions = {
center: paris,
zoom: zoomLevel,
zoomControl: false,
layers: [tileLayer]
};
map = new L.Map('leaflet-map', mapOptions);
L.control.zoom({ position: 'topright' }).addTo(map);
}
function createTileLayer() {
var tileSourceURL = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png';
var tileSourceOptions = {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
};
return new L.TileLayer(tileSourceURL, tileSourceOptions);
}
function createLayers() {
var arcDeTriomphe = L.marker([48.873747, 2.294935]).bindPopup("L'Arc de Triomphe"),
eiffelTower = L.marker([48.858093, 2.294694]).bindPopup('Eiffel Tower'),
sacreCoeur = L.marker([48.886666, 2.343061]) .bindPopup('Sacré-Cœur Basilica'),
pontDesArts = L.marker([48.858322, 2.337488]).bindPopup('Pont des Arts');
var layer1 = L.layerGroup([arcDeTriomphe, eiffelTower]);
var layer2 = L.layerGroup([sacreCoeur, pontDesArts]);
layers = {
'Layer 1': layer1,
'Layer 2': layer2
};
}
function addLayers() {
map.addLayer(layers['Layer 1']);
map.addLayer(layers['Layer 2']);
}
function toggleLayer(layerName) {
var layer = layers[layerName];
if (map.hasLayer(layer)) {
map.removeLayer(layer);
} else {
map.addLayer(layer);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment