根据一个变量不同的图层样式
Different layers styles according to a variable
我想在页面上显示几张地图,基本上它们都是一样的,只是它们有不同的图层,根据参数值不同。
我写的代码显示了所有地图上的图层,但样式总是采用循环中变量的最后一个值。在我的例子中总是取值 2.
我想知道我的错误到底在哪里,图层的样式没有根据循环值设置。
我写的部分脚本如下
for (variable = 0 ; variable <= 2 ; variable++){
vectorLayers[variable] = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/myLocation/myFiles',
format: new ol.format.GeoJSON()
}),
style: function(feature) {
id = feature.get('reading'+variable);
parameter = id[1];
fill.setColor(
parameter >= 0 && paramter < 0.10 ? lightBlue:
...);
return style;
}
});
样式函数不会像您期望的那样在 for 循环中执行。 for 循环将首先创建所有层,然后为每个层的每个特征调用样式函数。这就是为什么变量值总是 2 的原因。
仔细调试你会看到。
编辑 1:
编写一个创建矢量层的方法并在循环内调用它并传递变量值,以便正确维护该值。
for (variable = 0 ; variable <= 2 ; variable++){
vectorLayers[variable] = createVectorLayer(variable);
}
function createVectorLayer(variable) {
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/myLocation/myFiles',
format: new ol.format.GeoJSON()
}),
style: function(feature) {
id = feature.get('reading'+variable);
parameter = id[1];
fill.setColor(
parameter >= 0 && paramter < 0.10 ? lightBlue:
...);
return style;
}
});
return layer;
}
我想在页面上显示几张地图,基本上它们都是一样的,只是它们有不同的图层,根据参数值不同。
我写的代码显示了所有地图上的图层,但样式总是采用循环中变量的最后一个值。在我的例子中总是取值 2.
我想知道我的错误到底在哪里,图层的样式没有根据循环值设置。
我写的部分脚本如下
for (variable = 0 ; variable <= 2 ; variable++){
vectorLayers[variable] = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/myLocation/myFiles',
format: new ol.format.GeoJSON()
}),
style: function(feature) {
id = feature.get('reading'+variable);
parameter = id[1];
fill.setColor(
parameter >= 0 && paramter < 0.10 ? lightBlue:
...);
return style;
}
});
样式函数不会像您期望的那样在 for 循环中执行。 for 循环将首先创建所有层,然后为每个层的每个特征调用样式函数。这就是为什么变量值总是 2 的原因。 仔细调试你会看到。
编辑 1: 编写一个创建矢量层的方法并在循环内调用它并传递变量值,以便正确维护该值。
for (variable = 0 ; variable <= 2 ; variable++){
vectorLayers[variable] = createVectorLayer(variable);
}
function createVectorLayer(variable) {
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
url: '/myLocation/myFiles',
format: new ol.format.GeoJSON()
}),
style: function(feature) {
id = feature.get('reading'+variable);
parameter = id[1];
fill.setColor(
parameter >= 0 && paramter < 0.10 ? lightBlue:
...);
return style;
}
});
return layer;
}