1

Using OpenLayers with a Select interaction to select features, I'm attempting to convert the selected features to JSON for further processing within the select.on('select', ...) as per the code below.

select.on('select', function() {
     try {
         var json = new ol.format.GeoJSON().writeFeatures(select.getFeatures(), {});
         console.log(select.getFeatures().getLength());
         console.log(json);
         doStuffWithJSON(json);
     } catch(err) {
         console.log(err.message);
     }
});

However, the output from the two console.log() lines is:

2

{"type":"FeatureCollection","features":[]}

Ie, there are 2 features selected, but the GeoJSON includes no features.

What am I doing wrong here, and how I can I convert this to correct GeoJSON?

2
  • 2
    select.getFeatures() returns an OpenLayers collection, writeFeatures expects an array of features select.getFeatures().getArray()
    – Mike
    Jan 13 at 10:16
  • @Mike Thank you. That solved it of course. RTFM Son_of_a_Beach !!! :-) Want to write it up as an answer? Jan 14 at 2:20

1 Answer 1

0

As @Mike commented...

select.getFeatures() returns an OpenLayers collection, writeFeatures() expects an array of features so: select.getFeatures().getArray()

Fo my code, this now works as expected:

select.on('select', function() {
     try {
         var json = new ol.format.GeoJSON().writeFeatures(select.getFeatures().getArray(), {});
         console.log(select.getFeatures().getLength());
         console.log(json);
         doStuffWithJSON(json);
     } catch(err) {
         console.log(err.message);
     }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.