Javascript for Google Fusion Table layers working but trying to tidy code

不打扰是莪最后的温柔 提交于 2019-12-12 02:19:22

问题


I'm creating a map using Google Fusion Tables. It has several layers that are displayed or hidden depending on which checkboxes are ticked.

I created some code to turn the layers on/off, using a variable (layer10on) to keep track of whether each layer (layer10) was currently visible:

function toggleLayer10() { 
      if(layer10on) { layerl0.setOptions({map: null}); } 
      if(!layer10on) { layerl0.setOptions({map: map}); } 
      layer10on=!layer10on; 
} 

...

<input type="checkbox" checked onchange="toggleLayer10();" />

This works okay, but I don't want to duplicate this code for each of the checkboxes / layers so I'm trying to pass parameters for which checkbox is ticked, and which layer that relates to, but it's not working:

function toggleLayer(layerToChange,checkboxID) {
    if(!document.getElementById(checkboxID).checked) {
        layerToChange.setOptions({map: null});
    }
    if(document.getElementById(checkboxID).checked) {
        layerToChange.setOptions({map: map});
    }
}

...

<input value="layer10" id="check10" type="checkbox" checked onchange="toggleLayer(this.value,this.id);" />

It's been years since I did any coding so any help to let me know where I'm going wrong would be much appreciated.

Thanks,

nicola


回答1:


I showed an example toggleLayer in this answer but it's not that concise. this_layer is the actual FT Layer which should be a global. This checks whether the layer is visible or not.

function toggleLayer(this_layer)
{
   if( this_layer.getMap() ){
        this_layer.setMap(null);
   }else{
        this_layer.setMap(map);
   }
}

You need to have both your map as a global as well as your layers. I think, but have not tested that your checkboxes should look like:

<input value="layer10" id="check10" type="checkbox" checked onchange="toggleLayer(layer10);" />


来源:https://stackoverflow.com/questions/11107822/javascript-for-google-fusion-table-layers-working-but-trying-to-tidy-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!