[GIS] OpenLayers not displaying GeoJSON layer with features added after the fact

geojsonopenlayers

I have a vector layer with a GeoJSON source layer. OpenLayers isn't showing the layer when I try to add features using the addFeatures method:

myGeoJSONObject = { /* some GeoJSON */ };   

editLayer = new ol.layer.Vector({
    source : new ol.source.GeoJSON({
        style: styleFunction,
        defaultProjection: 'EPSG:4326',
        projection: "EPSG:3857"
    })
});

editLayer.getSource().addFeatures(myGeoJSONObject);

map.addLayer(editLayer);

Best Answer

The solution, I found, was to add the GeoJSON via the "object" property of the GeoJSON source object, like below:

editLayer = new ol.layer.Vector({
    source : new ol.source.GeoJSON({
        style: styleFunction,
        defaultProjection: 'EPSG:4326',
        projection: "EPSG:3857",
        object: myGeoJSONObject
    })
});

I also found that I had to have the projection options specified, otherwise I'd get an error about not finding the CRS when specifying the object property.

Related Question