[英]OpenLayers map duplicates when layer source is changed with an html select
I created an OpenLayers map that loads KML files.我创建了一个加载 KML 文件的 OpenLayers map。
I would like these files to be changed based on an html select.我希望根据 html select 更改这些文件。 It works well but the original map is not replaced: a second one is created below.它运行良好,但原始 map 未被替换:下面创建了第二个。
This behavior is visible here: https://jsfiddle.net/A_d_r_i/mazegr60/此行为在此处可见: 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();
}
I must definitely make a mistake in my onchange function.我肯定在我的 onchange function 中犯了一个错误。 If someone has an idea?如果有人有想法?
Thanks!谢谢!
You are creating a new map every time you call the function.每次调用 function 时,您都会创建一个新的 map。 Create the map and layers once, and only change the sources inside the function https://jsfiddle.net/ukbjp7oe/创建一次 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.