问题
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