如何循环使用OpenLayers.Layer的功能

时间:2014-05-23 10:18:38

标签: openlayers

这应该很简单,但是当我将图层加载为geojson 时,要素向量为空

var geojson1 = new OpenLayers.Layer.GML('layer_name', '/layer_path/file_name.geojson', {
    projection: new OpenLayers.Projection('EPSG:4326'),
    format: OpenLayers.Format.GeoJSON});

console.log(geojson1.features.length); // the result is 0, although there are shapes showing up on the map

可能是geojson装载机吗?

无论如何,这就是我100%确定这些功能的原因:因为下面的代码完美无缺。

//on click:
geojson1.events.on({
    'featureselected': function(e) {

        feature = e.feature;
        obj_name = feature.attributes.NAME;

        newAction(obj_name);

        selectCtrl.unselect(feature);

    }
});

所有这一切的最终目标是以编程方式为每个功能创建一个新属性:

for(var featureCount=0; featureCount < geojson1.features.length; featureCount++){
    console.log(geojson1.features[featureCount].attributes.NAME);
    //TODO: add new attribute to feature ( geojson1.features[featureCount].attributes.ID = custom_ID )
} 

1 个答案:

答案 0 :(得分:0)

如果你在这里查看GeoJSON读取函数http://trac.osgeo.org/openlayers/browser/trunk/openlayers/lib/OpenLayers/Format/GeoJSON.js的源代码,你会看到它返回的是OpenLayers.Feature.Vector或OpenLayers.Geometry,具体取决于JSON的结构。您正在尝试将其加载到OpenLayers.Layer.GML类中,我怀疑这是问题所在。如果你需要GML,那么你需要在Feature.Vector中读取JSON,然后使用OpenLayers.Format.GML写入方法将其写回。

如果您想检查您的JSON是否有效,请使用http://jsonlint.com/