我正在尝试构建一个包含多个可以打开和关闭的图层的 web 地图。最初绘制地图时没有任何问题,但是当我尝试关闭任何图层时,会在现有地图下方添加一个新地图(而不是替换它)。
当我关闭图层时,会调用 javascript refresh() 函数。该函数需要重建要绘制的图层列表,然后再次调用构建地图的函数。我希望这只会替换现有的,而是在下面添加了一个新地图。
...
...
<script type="text/javascript" src="ol.js"></script>
<script defer="defer" type="text/javascript">
function onLOAD()
{
var my_layers = 'layer_1, \
layer_2, \
layer_3, \
...'
init(my_layers);
}
function init(my_layers){
//The bounding box of Lund:lund_address_point
var extent = [13.1267,55.6770,13.2601,55.7597];
//Initial view
var view = new ol.View({
center: ol.proj.transform([13.192927, 55.708944], 'EPSG:4326', 'EPSG:3857'),
zoom: 13
});
//The source for the layers
var wmsSource = new ol.source.ImageWMS({
url: 'http://localhost:8080/geoserver/Test/wms',
params: {
'LAYERS': my_layers
},
serverType: 'geoserver'
});
//OpenStreetMap background and my_layers
var layers = [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Image({
source: wmsSource
})
];
//Bind the map object to our "map" div and add some extra functionality
var map = new ol.Map({
layers: layers,
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}).extend([
//Extra functionality of the map
//Control for displaying coordinates
new ol.control.MousePosition({
coordinateFormat: ol.coordinate.createStringXY(4),
projection: 'EPSG:4326',
className: 'custom-mouse-position',
target: document.getElementById('location'),
undefinedHTML: ' '
}),
//Control for displaying a scale line
new ol.control.ScaleLine({
target: document.getElementById('scale-line')
}),
//Control for zooming to a defined extent
new ol.control.ZoomToExtent({
extent: ol.proj.transform(extent, 'EPSG:4326', 'EPSG:3857')
})
]),
target: 'map',
view: view
});
}
function refresh(){
my_layers='';
if (layer_1.checked) my_layers = my_layers + "layer_1,";
if (layer_2.checked) my_layers = my_layers + "layer_2,";
if (layer_3.checked) my_layers = my_layers + "layer_3,";
...
if (my_layers.length > 1){
my_layers = my_layers.substring(0,my_layers.length-1);
}
init(my_layers);
}
</script>
</head>
<body onload="onLOAD()">
<div>
<br><input type="checkbox" id="layer_1" value="layer_1" checked="checked" onClick="refresh()">Layer_1
<br><input type="checkbox" id="layer_2" value="layer_2" checked="checked" onClick="refresh()">Layer_2
<br><input type="checkbox" id="layer_3" value="layer_3" checked="checked" onClick="refresh()">Layer_3
...
...
</div>
<br>
<div id="map"></div>
<br>
<div id="wrapper">
<div id="location"></div>
<br>
<div id="scale-line" class="scale-line"></div>
</div>
...
...