Search code examples
javascriptgeojsonopenlayers-3

Adding geojson layer to openlayers 3


I have gone through a few different examples on this and nothing ever seems to work. I am trying to simply draw a point on the map using GeoJSON as the source. Here is what I currently have:

var staticGeo = new ol.source.GeoJSON(({
    object: {
        type: 'Feature Collection',
        crs: {
           type: 'name',
           properties: {name: 'EPSG:4326'}
        },
        features: [{
           type: 'Feature',
           geometry: {
               type: 'Point',
               coordinates: [0,0]
           }
        }]
     },
     projection: 'EPSG:3857'
   }));

   var vectorSource = new ol.source.Vector({
       source: staticGeo
   });

   var vectorLayer = new ol.layer.Vector({
       source: vectorSource,
       style: new ol.style.Style({
           fill: new ol.style.Fill({
                color: 'rgba(255,255,255,0.2)'
           }),
           stroke: new ol.style.Stroke({
                color: 'blue',
                width: 1
           })
        })
     })

     this.map.addLayer(vectorLayer);

this.map refers to the ol.Map object that is working. This overall seems like a lot of code to do something that should be seemingly trivial (maybe I am doing something wrong?).


Solution

  • From OL 3.5.0 you will add geojson like this:

    var geojsonObject = {
        'type': 'FeatureCollection',
        'crs': {
            'type': 'name',
            'properties': {
                'name': 'EPSG:4326'
            }
        },
        'features': [
            {
                'type': 'Feature',
                'geometry': {
                    'type': 'Point',
                    'coordinates': [21.54967, 38.70250]
                }
            }
        ]
    };
    var features = new ol.format.GeoJSON().readFeatures(geojsonObject, {
        featureProjection: 'EPSG:3857'
    });
    var vectorSource = new ol.source.Vector({
      features: features
    });
    

    Note the projection coordinates.

    http://jsfiddle.net/jonataswalker/w5uuxhov/