[GIS] OpenLayers3 addLayer geoJSON

geojsonlayersopenlayers

I'm trying to add a geoJSON layer to my OpenLayers3 map following this example. Below is my GeoJSON

{"type":"FeatureCollection",
 "crs":{"type":"name","properties":{"name":"EPSG:4326"}},
 "features":[
  {"type":"Feature",
    "geometry":{
      "type":"Point",
      "coordinates":[-78.6569,37.4316]},
    "properties":{
      "Title":"Test ",
      "Assessment":"Test",
      "State":"Virginia",
      "Brief Description":"This ia a brief Descript",
      "Details":"<div><p>Here are the details</p></div>"}}]}

When I add this layer to the map I get a point at [0,0] instead of the coordinates in the json file.

function loadGeoJSON(geo)
{
    console.log('loading Geo JSON');
    console.log(JSON.stringify(geo));
    var vectorSource = new ol.source.Vector({
        features:(new ol.format.GeoJSON()).readFeatures(geo)
    });
    var vectorLayer = new ol.layer.Vector({
        source:vectorSource,
        style:styleFunction
    })
    map.addLayer(vectorLayer);
    for(var i = 0; i < vectorLayer.getSource().getFeatures().length; i++){
        console.log(vectorLayer.getSource().getFeatures()[i].getGeometry());
    }
}

Best Answer

You need to manually reproject your features. GeoJSON data recommended coordinates are using EPSG:4326 but the map is using EPSG:3857 (Spherical Mercator)

your

(new ol.format.GeoJSON()).readFeatures(geo)

should be

var features = (new ol.format.GeoJSON()).readFeatures(json, {
  dataProjection : 'EPSG:4326', # Default, could be removed
  featureProjection: 'EPSG:3857'
});

If you do like in http://openlayers.org/en/master/examples/select-features.html (below), the transformation from EPSG 4326 to EPSG 3857 would be automatic

var vector = new ol.layer.Vector({
  source: new ol.source.Vector({
    url: 'https://openlayers.org/en/v3.19.1/examples/data/geojson/countries.geojson',
    format: new ol.format.GeoJSON()
  })
});