1

I have an html toggle button and try to toggle update between two layers (baselayer and earthlayer) when it's changed.

I am assigning a variable and change the value to the corresponding layer. Perhaps something is wrong and the layer is not getting updated.

var MapView = baseLayer;
$("#mapview").change(function () {//when toggle button is changed
  if ($(this).is(':checked'))
    MapView = earthlayer;
  else
    MapView = baseLayer;  
});

var map = new ol.Map({
  target: 'map',
  layers: [MapView],
  view: new ol.View({
    center: ol.proj.fromLonLat([33.33386, 35.14710]),
    zoom: 14
  })
});
2

With var map = new ol.Map you create new map with each toggle. Map creation has to be moved out of toggle processing. There you just add/remove required layer, something like this:

var mapLayer = baseLayer;
var map = new ol.Map({
  target: 'map',
  layers: [mapLayer],
  view: new ol.View({
    center: ol.proj.fromLonLat([33.33386, 35.14710]),
    zoom: 14
  })
});

$("#mapview").change(function () {//when toggle button is changed
  var newMapLayer;

  if ($(this).is(':checked'))
    newMapLayer = earthlayer;
  else
    newMapLayer = baseLayer;  

  if (newMapLayer != mapLayer) {
    map.addLayer(newMapLayer);
    map.removeLayer(mapLayer);
    mapLayer = newMapLayer;
  }
});
0

You could do what most layer switchers do and set the visibility (a little refinement is needed to set the initial visibility)

var map = new ol.Map({
  target: 'map',
  layers: [baseLayer, earthlayer],
  view: new ol.View({
    center: ol.proj.fromLonLat([33.33386, 35.14710]),
    zoom: 14
  })
});

$("#mapview").change(function () {//when toggle button is changed
  var checked = $(this).is(':checked');
  baseLayer.setVisible(!checked);
  earthLayer.setVisible(checked);
});
0

Here is what i did and worked. Note that i add each layer at position 0. So it does not replace any other layer. It adds them as baselayers.

 $("#mapview").change(function () {
  if ($(this).is(':checked')){
    map.removeLayer(roadlayer);
    map.getLayers().insertAt(0, earthlayer);
  }
  else{
    map.removeLayer(earthlayer);
    map.getLayers().insertAt(0, roadlayer);
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.