Javascript examples for Leaflet:Map
Leafletjs dynamically bound map to visible overlays
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="https://unpkg.com/leaflet@1.1.0/dist/leaflet.css"> <script type="text/javascript" src="https://unpkg.com/leaflet@1.1.0/dist/leaflet-src.js"></script> <script type="text/javascript" src="https://unpkg.com/leaflet.featuregroup.subgroup@1.0.2/dist/leaflet.featuregroup.subgroup-src.js"></script> <style id="compiled-css" type="text/css"> #map {/*from w w w . jav a 2s .co m*/ height: 500px; } </style> <script type="text/javascript"> window.onload=function(){ var map = L.map("map"); L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png").addTo(map); map.setView([48.85, 2.35], 12); var parentGroup = L.featureGroup().addTo(map), subGroup1 = L.featureGroup.subGroup(parentGroup), subGroup2 = L.featureGroup.subGroup(parentGroup); for (var i = 0; i < 10; i += 1) { L.marker(getRandomLatLng()).addTo(subGroup1); } for (i = 0; i < 10; i += 1) { L.marker(getRandomLatLng2()).addTo(subGroup2); } var overlays = { 'SubGroup 1': subGroup1, 'SubGroup 2': subGroup2 }; L.control.layers(null, overlays, { collapsed: false }).addTo(map); map.on('overlayadd overlayremove', function () { var bounds = parentGroup.getBounds(); if (bounds.isValid()) { map.fitBounds(bounds); } }); function getRandomLatLng() { return [ 48.8 + 0.05 * Math.random(), 2.25 + 0.1 * Math.random() ]; } function getRandomLatLng2() { return [ 48.85 + 0.05 * Math.random(), 2.35 + 0.1 * Math.random() ]; } } </script> </head> <body> <div id="map"></div> </body> </html>