spierepf
spierepf

Reputation: 2934

How to manually load a GeoJSON layer in OpenLayers

I am trying to load some GeoJSON from a URL.

When I pass a url to the vector source, everything works as expected:

function aircraftLayerFunction() {
  var format = new ol.format.GeoJSON();
  return new ol.layer.Vector({
    source: new ol.source.Vector({wrapX: false, url:"/aircraft", format: format}),
    style: function (feature, resolution) {
      return new ol.style.Style({
        image: new ol.style.Circle({
          radius: 3,
          fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.1)'}),
          stroke: new ol.style.Stroke({color: 'red', width: 1})
        }),
        text: new ol.style.Text({
          text: feature.get('name'),
          offsetY: 8
        })
      });
    }
  });
}

However, when I pass a loader instead, I get nothing, not even an error message on the console:

function aircraftLayerFunction() {
  var format = new ol.format.GeoJSON();
  return new ol.layer.Vector({
    source: new ol.source.Vector({wrapX: false, format: format, loader: function(extent, resolution, projection) {
        $.getJSON("/aircraft", function(response) {
          format.readFeatures(response)
        });
      }
    }),
    style: function (feature, resolution) {
      return new ol.style.Style({
        image: new ol.style.Circle({
          radius: 3,
          fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.1)'}),
          stroke: new ol.style.Stroke({color: 'red', width: 1})
        }),
        text: new ol.style.Text({
          text: feature.get('name'),
          offsetY: 8
        })
      });
    }
  });
}

I'd like to be able to pass a loader instead of a url so that I have an opportunity to alter the response before it's features are added to the layer.

In particular I would like to use GraphQL to replace my /aircraft REST endpoint with something a little more flexible. However GraphQL keeps adding 'data' and 'aircraft' nodes to my response...

Upvotes: 0

Views: 612

Answers (1)

Mike
Mike

Reputation: 17972

readFeatures simply returns an array of features. The loader needs to add them to the source (in the view projection)

  loader: function(extent, resolution, projection) {
    var source = this;
    $.getJSON("/aircraft", function(response) {
      source.addFeatures(format.readFeatures(response, { featureProjection: projection }));
    });
  }

Upvotes: 1

Related Questions