Son of a Beach
Son of a Beach

Reputation: 1779

OpenLayers GeoJSON Layer projection not working

Using the code below, I've been unable to get my single GeoJSON point feature to appear on the map. Or possibly if it does appear on the map in the correct location. It appears in Germany, whereas it should appear in Tasmania, Australia. Same location it appears at if I provide no projection at all. Therefore it seems that there is some problem with the way I'm setting the projection.

I have a feeling that I'm using defaultDataProjection and/or featureProjection incorrectly, but I find the documentation to be fairly unclear on how these should be used.

The same projection works on my other (non-GeoJSON) layers OK.

How can I correct my code to get this to work?

var geojsonObject = {"type":"FeatureCollection","features":[{"geometry":{"type":"Point","coordinates":[503619.026899999939,5420925.347199999727]},"properties":{"label":{}},"type":"Feature"}]};

proj4.defs('layerProj', '+proj=utm +zone=55 +south +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs ')

var vectorSource = new ol.source.Vector({
    features: (new ol.format.GeoJSON({
        defaultDataProjection: 'layerProj',
    }).readFeatures(geojsonObject, { featureProjection: 'layerProj' }))
})

var vectorLayer = new ol.layer.Vector({
  source: vectorSource,
  style: new ol.style.Style({image: new ol.style.Circle({fill: new ol.style.Fill({color: '#8888FF'}), radius: 10, points: 0})}),
});
    
map.addLayer(vectorLayer);

Upvotes: 1

Views: 875

Answers (1)

Mike
Mike

Reputation: 17962

Your format: should be features: Also defaultDataProjection in the GeoJSON options in OpenLayers 4 changes to dataProjection in later version, so it may be better to specify dataProjection in the readFeatures options where the name is the same in all versions. featureProjection should always be set to the view projection

        features: new ol.format.GeoJSON().readFeatures(geojsonObject, { 
          dataProjection: 'layerProj',
          featureProjection: map.getView().getProjection()
        })

If you are using OpenLayers 5 or above you will also need to register proj4 after the layerproj definition

ol.proj.proj4.register(proj4);

Upvotes: 4

Related Questions