Search code examples
javascriptgisopenlayers

How to force OpenLayers to load source?


I have noticed that OpenLayers will not "load" source unless it is assigned to a layer which is assigned to map.

This code does console.log() with number of features in a KML layer:

const layer = new Heatmap({
  source: new VectorSource({
    url: file,
    format: new KML({
      extractStyles: false,
    }),
  }),
});

layer.getSource().on('change', function (evt: any) {
  var source = evt.target;
  if (source.getState() === 'ready') {
    var numFeatures = source.getFeatures().length;
    console.log('Count after change: ' + numFeatures);
  }
});

this.map.addLayer(layer);

If I remove this line:

this.map.addLayer(layer);

it doesn't output anything. I have a feeling that OpenLayers ignores it as it is not used. Is there a way to force OpenLayers to load it?

(context - I would like to merge features coming from multiple sources into one thus I don't want to directly load them onto the map. I'd like them to load so I can get features and then merge these features into one array and then display this array on the map)


Solution

  • You can combine features from multiple files and formats by fetching the urls and using the format's readFeatures() method

    const vectorSource = new VectorSource();
    const layer = new  Heatmap({
      source: vectorSource,
    });
    
    function loadFromUrl (url, format) {
      fetch(url).then(function (response) {
        response.text().then(function (result) {
          vectorSouce.addFeatures(
            format.readFeatures(result, {
              dataProjection: 'EPSG:4326',
              featureProjection: map.getView().getProjection(),
            })
          }
        });
    }
    
    loadFromUrl(kmlFile, new KML({extractStyles: false}));
    loadFromUrl(geojsonFile, new GeoJSON());