Add GeoJSON layer to OpenLayers 3
FYI... I believe this has changed for OL3 V3.5.0, so gcarrillo's answer would be:
new ol.layer.Vector({
title: 'added Layer',
source: new ol.source.Vector({
url: 'mygeojson.json',
format: new ol.format.GeoJSON()
})
})
You can see the changes here: https://github.com/openlayers/ol3/blob/master/changelog/upgrade-notes.md#v350
When you define your vector source, put the projection setting pointing to the target coordinate reference system (see the docs):
new ol.layer.Vector({
title: 'added Layer',
source: new ol.source.GeoJSON({
projection : 'EPSG:3857',
url: 'mygeojson.json'
})
})
Look at this example (using your sample data): http://jsfiddle.net/zzahmbff/4/
Perhaps this resource can help you to see different ways to load vector data: http://acanimal.github.io/thebookofopenlayers3/chapter03_03_vector_source.html
The OpenLayers Vector API is changing a lot. I have a working sample with OpenLayers 3.16.0.
It's important that you must define featureProjection: 'EPSG:3857'
in the options of readFeatures
like this:
.readFeatures(_geojson_object, { featureProjection: 'EPSG:3857' })
Reference can be found at https://github.com/openlayers/ol3/blob/master/changelog/upgrade-notes.md#v350
Example:
_geojson_vectorSource = new ol.source.Vector({
features: (new ol.format.GeoJSON()).readFeatures(_geojson_object, { featureProjection: 'EPSG:3857' })
});
_geojson_vectorLayer = new ol.layer.Vector({
source: _geojson_vectorSource,
style: styleFunction
});
map.addLayer(_geojson_vectorLayer);
Note: styleFunction
var image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({ color: 'red', width: 1 })
});
var styles = {
'Point': new ol.style.Style({
image: image
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiLineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'green',
width: 1
})
}),
'MultiPoint': new ol.style.Style({
image: image
}),
'MultiPolygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'yellow',
width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 0.1)'
})
}),
'Polygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'blue',
lineDash: [4],
width: 3
}),
fill: new ol.style.Fill({
color: 'rgba(0, 0, 255, 0.1)'
})
}),
'GeometryCollection': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'magenta',
width: 2
}),
fill: new ol.style.Fill({
color: 'magenta'
}),
image: new ol.style.Circle({
radius: 10,
fill: null,
stroke: new ol.style.Stroke({
color: 'magenta'
})
})
}),
'Circle': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red',
width: 2
}),
fill: new ol.style.Fill({
color: 'rgba(255,0,0,0.2)'
})
})
};
var styleFunction = function (feature) {
return styles[feature.getGeometry().getType()];
};