[英]OpenLayers map duplicates when layer source is changed with an html select
我創建了一個加載 KML 文件的 OpenLayers map。
我希望根據 html select 更改這些文件。 它運行良好,但原始 map 未被替換:下面創建了第二個。
此行為在此處可見: https://jsfiddle.net/A_d_r_i/mazegr60/
window.onload = function go() {
var choix = document.getElementById('choix');
choix.onchange = function() {
title.innerHTML = this.options[this.selectedIndex].text;
test.innerHTML = this.options[this.selectedIndex].getAttribute('name');
var name = this.options[this.selectedIndex].getAttribute('name');
var url_bdd1 = 'URL FOR KML' + name + '.kml';
var url_bdd2 = 'URL FOR KML' + name + '.kml';
var layer_bdd1 = new ol.layer.Vector({
source : new ol.source.Vector({
format : new ol.format.KML(),
url : url_bdd1
})
});
var layer_bdd2 = new ol.layer.Vector({
source : new ol.source.Vector({
format : new ol.format.KML(),
url : url_bdd2
})
});
var layer_osm = new ol.layer.Tile({
source: new ol.source.OSM(),
opacity: 1
});
var map = new ol.Map({
target: 'map',
layers: [
layer_osm,
layer_bdd2,
layer_bdd1
],
view: new ol.View({
center: ol.proj.transform([2, 47], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
};
choix.onchange();
}
我肯定在我的 onchange function 中犯了一個錯誤。 如果有人有想法?
謝謝!
每次調用 function 時,您都會創建一個新的 map。 創建一次 map 和層,並且只更改 function https://jsfiddle.net/ukbjp7oe/內的源
window.onload = function go() {
var layer_bdd1 = new ol.layer.Vector();
var layer_bdd2 = new ol.layer.Vector();
var layer_osm = new ol.layer.Tile({
source: new ol.source.OSM(),
opacity: 1
});
var map = new ol.Map({
target: 'map',
layers: [
layer_osm,
layer_bdd2,
layer_bdd1
],
view: new ol.View({
center: ol.proj.transform([2, 47], 'EPSG:4326', 'EPSG:3857'),
zoom: 6
})
});
var choix = document.getElementById('choix');
choix.onchange = function() {
title.innerHTML = this.options[this.selectedIndex].text;
test.innerHTML = this.options[this.selectedIndex].getAttribute('name');
var name = this.options[this.selectedIndex].getAttribute('name');
var url_bdd1 = 'URL FOR KML' + name + '.kml';
var url_bdd2 = 'URL FOR KML' + name + '.kml';
layer_bdd1.setSource(
new ol.source.Vector({
format: new ol.format.KML(),
url: url_bdd1
})
);
layer_bdd2.setSource(
new ol.source.Vector({
format: new ol.format.KML(),
url: url_bdd2
})
);
};
choix.onchange();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.