0

I have this basemap selection panel:

  // Basemap selection  
  var baseMaps = L.control.layers({
    'Grey Canvas': L.mapbox.tileLayer('mapbox.light').addTo(map),
    'Dark Canvas': L.mapbox.tileLayer('mapbox.dark'),
    'Street Canvas': L.mapbox.tileLayer('mapbox.streets'),
    'Simple Canvas': L.mapbox.tileLayer('mapbox.streets-basic'),
    'Emerald Canvas': L.mapbox.tileLayer('mapbox.outdoors')
  }).addTo(map);

  // Add cartoDB layer, default is checked on
  var cdb_layer = cartodb.createLayer(map, 'LINK')
    .addTo(map).on('done', function(layer) {
      baseMaps.addOverlay(layer, 'Population');
    });

  // Add population density or other layers, default check is off
  var cdb_layer2 = cartodb.createLayer(map, 'LINK', {
      legends: false
    })
    .on('done', function(layer) {
      baseMaps.addOverlay(layer, 'Population Density');
    });
  })

The first section in the panel lets the user choose a mapbox basemap, the second section are 2 cartodb layers. Currently, when one box is checked, the other can also be checked. How do I make it so that when one box is checked, the other turns off and when the other box is checked, the current checked box turns off?

Thanks a lot.

1 Answers1

0

I had done something similar to this a while back, although I opted for checkboxes for my layers, since there were times I wanted multiple layers to be turned on simultaneously. First off, you'll need to make radio buttons in your html.

<input type="radio" name="map_layer" id="layer_1" checked>Layer 1<br>
<input type="radio" name="map_layer" id="layer_2">Layer 2

If you're not familiar with radio buttons, it is very important to note that all of the buttons in your group need to have the same name - that way, there can only be one value at a time.

Now for your script, I think you're going to want to do something like this (reaching into my memory here)...

var layerSource = {
  user_name: 'YOUR USERNAME HERE',
  type: 'cartodb',
  sublayers: [{sql: "SELECT * FROM population"},
             {sql: "SELECT * FROM population_density"}]
};

// STORE SUBLAYERS
var sublayers = [];                

// ADD LAYER TO MAP
cartodb.createLayer(map,layerSource)
.addTo(map)
.done(function(layer) {

for (i = 0; i < layer.getSubLayerCount(); i++) {
  sublayers[i] = layer.getSubLayer(i);
};

var cdb_layer = sublayers[0];
var cdb_layer2 = sublayers[1];

cdb_layer2.hide();

$("input[name=map_layer]:radio").change(function () {
  if($('#layer_1').is(':checked')){
    cdb_layer.show();
    cdb_layer2.hide();
   }
  if($('#layer_2').is(':checked')){
    cdb_layer2.show();
    cdb_layer.hide();
   }
 });
});

I hope that this is helpful. This is, more or less, the way that I was able to make this work, but without having your full example to test, I can't say for sure.

skwidbreth
  • 7,888
  • 11
  • 58
  • 105