0
votes

I want to download features in geoJson format from a service and then add the features in it to a new layer on my map. I can download the features ok, I'm stuck as to how to add them to the map after the download. I do not want to let OL read the file directly from the url as shown in every example I can find, since I want more control over when the features will be downloaded or what to do if the download fails for some reason. I'm trying this (data contains my geoJson featurecollection):

var nwLayer = new ol.layer.Vector({
    title: 'My Title',
    source: new ol.source.Vector({
        features: data.features,
        format: new ol.format.GeoJSON()
    }),
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill( { color: "yellow" } )
        })
    })
} );
map.addLayer(nwLayer);

This results in an error somewhere inside the ol library, apparently the ol feature type is not the same as a geoJson feature, it requires a getId() function. I also tried to add the data as a whole:

features: data,

This has no visual effect at all. How can I do this?

1

1 Answers

2
votes

You are correct, OpenLayer features are not GeoJSON feature objects. To transform GeoJSON to OpenLayers features, use the readFeatures method of ol.format.GeoJSON.

With the rest of your example code:

var nwLayer = new ol.layer.Vector({
    title: 'My Title',
    source: new ol.source.Vector({
        features: (new ol.format.GeoJSON()).readFeatures(data)
    }),
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 7,
            fill: new ol.style.Fill( { color: "yellow" } )
        })
    })
});
map.addLayer(nwLayer);