1
votes

I'm using Openlayers 3 and want to add a layer, in which the answer of the TurfJS function "merge" should be the source. Adding a GeoJSON-Layer directly in OpenLayers 3 is not problem and works fine. But when i load the GeoJSON-File in a variable an the use turf.merge(source), this can't be added in a layer anymore. I already tried to convert the answer of turf.merge in a FeatureCollection and add this as the layer source, but that's also not working

//define source (contains Polygons)
        var source = new ol.source.Vector({
      url: 'geb03_f_source.geojson',
      format: new ol.format.GeoJSON({
          })
    });

//Merge source
var merged = turf.merge(source);

//define layer
var vectorLayer = new ol.layer.Vector({
  source: merged,
  projection: 'EPSG:3857'
});

//add layer to map
map.addLayer(vectorLayer);

The problem I see is that when loading the page, the GeoJSON-File is not loaded although it should.

But just loading and displaying the File works:

var source = new ol.source.Vector({
  url: 'geb03_f_source.geojson',
  format: new ol.format.GeoJSON({
      })
});

var vectorLayer = new ol.layer.Vector({
  source: source,
  projection: 'EPSG:3857'
});

map.addLayer(vectorLayer);

Maybe something with the GeoJSON-Fomat is wrong when using turfs merge? I'm happy for every help!

1
the console shows a "TypeError: t.features is undefined". domething with the format of the loaded GeoJSON-Feature seemswrong...user2010988
Don't forget to give a feedback. You got your answer.Jonatas Walker

1 Answers

0
votes

Turf JS uses GeoJSON as input- and output, you provide an OpenLayers vector source object as input. So you need to change that.

One option is to use theloader option of ol.source.Vector instead of url and format, to directly merge the GeoJSON polygons before adding it to the source.

Another option is to retransform the ol source to GeoJSON, something like:

var geoJSONFormat = new ol.format.GeoJSON({});

var source = new ol.source.Vector({
  url: 'geb03_f_source.geojson',
  format: geoJSONFormat
});

var mergedSource = new ol.source.Vector({});

source.on('change', function(){
  var sourceJSON = geoJSONFormat.writeFeaturesObject(source.getFeatures());
  var merged = turf.merge(sourceJSON);
  var mergedOLFeature = geoJSONFormat.readFeature(merged);
  mergedSource.clear();
  mergedSource.addFeature(mergedOLFeature);
});