我有一个使用Javascript创建的对象数组。对象是地图图层,并具有相关的各种属性。在创建时,它们被推入阵列。以下是简化示例
var activeLayers = [];
var mapLayer1 = new mapLayer();
mapLayer1.name = 'roads';
mapLayer1.class = 'infrastucture';
mapLayer1.type = 'line';
activeLayers.push(mapLayer1);
var mapLayer2 = new mapLayer();
mapLayer2.name = 'cities';
mapLayer2.class = 'infrastucture';
mapLayer2.type = 'point';
activeLayers.push(mapLayer2);
var mapLayer3 = new mapLayer();
mapLayer3.name = 'counties';
mapLayer3.class = 'boundaries';
mapLayer3.type = 'polygon';
activeLayers.push(mapLayer3);
var mapLayer4 = new mapLayer();
mapLayer4.name = 'zoningDistricts';
mapLayer4.class = 'political';
mapLayer4.type = 'polygon';
activeLayers.push(mapLayer4);
我想要做的是强制我的地图不允许同时显示多个type == polygon图层。我想迭代数组'activeLayers',如果type == polygon.length> 1然后我想从地图中删除最旧的。从地图中删除图层是通过
的功能完成的mapLayer3.hide();
在上面的数组中,mapLayer3是一个多边形,并在mapLayer4之前添加,并将从地图中隐藏。
谢谢你看看。
答案 0 :(得分:1)
试试这个。
var prevPoly = null;
for(var i = 0;i < activeLayers.length;i++){
if(activeLayers[i].type == 'polygon'){
if(prevPoly){
prevPoly.hide();
break;
}
else{
prevPoly = activeLayers[i];
}
}
}
}
答案 1 :(得分:1)
可以说,您应该使用一个对象来存储活动图层,使用类型的键值对来显示可见图。当您使地图图层可见时,将对象属性设置为要显示的地图
function activeLayers = {};
function showMapLayer(layer) {
activeLayers[layer.type] = mapLayer;
}
function hideMapLayer(layer) {
activeLayers[layer.type] = null;
}
然后,您可以使用for ... in循环遍历可见图层
var layer;
for (layer in activeLayers)
{
if (layer && activeLayers.hasOwnProperty(layer)) {
// this is an active layer, do something with it
}
}
我确实意识到这不会保留您添加图层的顺序,因此您可以始终使用对象作为指导来跟踪此情况。 (我将以示例更新)