OpenLayers – How to Resolve GeoJSON Projection Issues in OpenLayers

geojsonopenlayers

I have a basic geojson source, which is

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "id": "30cde2b6-767d-426d-8f41-c6b0fad78343",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -75.9337031788254,
          38.8970092675465
        ]
      },
      "properties": {
        "Title": "Test Title",
        "DateCreated": "2018-07-10T13:38:59Z"
      }
    }
  ],
  "crs": {
    "properties": {
      "name": "EPSG:4326"
    },
    "type": "name"
  }
}

and want to show it on a simple map like so:

var vectorSource = new ol.source.Vector({
        features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
      });

      var vectorLayer = new ol.layer.Vector({
        source: vectorSource,
        style: styleFunction
      });

      var map = new ol.Map({
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          vectorLayer
        ],
        target: 'map',
        controls: ol.control.defaults({
          attributionOptions: {
            collapsible: false
          }
        }),
        view: new ol.View({
          center: [0, 0],
          zoom: 2
        })
      });

my actual code can be found here: https://codepen.io/vishnu4/pen/rqoYzp

Why is this displaying the point at 0,0? I have the projection declared in the geojson, and putting it in the layer seems to have no effect. what else am i missing?

Best Answer

The features are in EPSG:4326 coordinates, they need to be converted to 3857.

either:

new ol.format.GeoJSON({ featureProjection: 'EPSG:3857' }).readFeatures(geojsonObject)

or:

new ol.format.GeoJSON().readFeatures(geojsonObject,{ featureProjection: 'EPSG:3857' })

You don't need to specify a projection for a vector layer, it's not used.

Related Question