简体   繁体   中英

OpenLayers 3 get vector feature/attribute without adding layer to map

I need to access a vector layer's attributions, as it contains information I will use logically within my OL3 implementation.

I can do this as follows:

//Adding local layer
var layer_to_return = new ol.layer.Vector({
       source: new ol.source.Vector({
         url: "/positional_data/Flight_Test_Position_Data_GEOJSON_point.geojson",
          format: new ol.format.GeoJSON(),
          style:Custom_Style,
          visible:false
    })
});

map.addLayer(layer_to_return);

Notice that I have set visible:false. It appears that I need to add the layer to the map in order to access the attributes with the following:

layer_to_return.getSource().once('change',function(e){
    if(layer_to_return.getSource().getState() === 'ready') {
        layer_to_return.getSource().forEachFeature(function(feature){
           var time = feature.get('time(millisecond)'); 
           console.log(time);
        }
     );          
}
});

If I don't include the map.addLayer(layer_to_return) statement then the above doesn't work, it just doesn't run the whole change event.

If I take the change event handler away, the time variable returns blank, possibly because the layer hasn't loaded yet.

Is there a way to get access to the layer attributes without adding the layer to the map?

just make a post-get request to get your json file and then use ol.format.GeoJSON class to parse the features. Something like that should do your job.

$.ajax('/positional_data/Flight_Test_Position_Data_GEOJSON_point.geojson', {
        type: 'GET'            
  }).done(function (geojson) {
//HERE IS YOUR KEY CLASS
var features = new ol.format.GeoJSON().readFeatures(geojson);
//NOW YOU CAN ITERATE THROUGH YOUR FEATURES AND GET ATTR
//LIKE
for (var i=0;i<features.length;i++){
var attr = features[i].get('attr');
}
}).fail(function (jqXHR, textStatus) {
 alert('geojson fail to load');
});)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM