Leaflet - display GeoJSON data only when certain layer is selected - Javascript Leaflet

Javascript examples for Leaflet:Layer

Description

Leaflet - display GeoJSON data only when certain layer is selected

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"> 
      <script type="text/javascript" src="http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> 
      <script type="text/javascript" src="http://leafletjs.com/examples/us-states.js"></script> 
      <script type="text/javascript" src="https://raw.githubusercontent.com/vogdb/Leaflet.ActiveLayers/master/src/ActiveLayers.js"></script> 
      <style id="compiled-css" type="text/css">

body {//from   w w w.  j a va  2  s .  co  m
   padding: 0;
   margin: 0;
   height: 100%;
   width: 100%;
}
#map {
   position: absolute;
   top: 0;
   left: 0;
   height: 100%;
   width: 100%;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){
var OpenStreetMap_Mapnik = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
   maxZoom: 19,
   attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
var OpenStreetMap_BlackAndWhite = L.tileLayer('http://{s}.tiles.wmflabs.org/bw-mapnik/{z}/{x}/{y}.png', {
   maxZoom: 18,
   attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});
// initialize map
var map = L.map('map', {
    center: [37.8, -96],
    zoom: 4,
    layers: [OpenStreetMap_Mapnik]
});
var baseMaps = {
    "Mapnik": OpenStreetMap_Mapnik,
    "Black and White": OpenStreetMap_BlackAndWhite
};
loadstates = L.geoJson(statesData);
var states = {
    "US States": loadstates
};
var control = L.control.activeLayers(baseMaps);
control.addTo(map);
//alert(control.getActiveBaseLayer().name);
map.on('baselayerchange', baseLayerChange);
function baseLayerChange(){
   if (control.getActiveBaseLayer().name == 'Black and White') {
      map.addLayer(loadstates);
   }
   else{
      map.removeLayer(loadstates);
   }
}
    }

      </script> 
   </head> 
   <body> 
      <div id="map"></div>  
   </body>
</html>

Related Tutorials