JavaScript – Fixing GeoJSON Import Error in OpenLayers 3

javascriptopenlayers

I have a GeoJSON file that I need to upload using OpenLayers, I use the following JavaScript code as follow:

 function InitMap()
  {
    var vectorSource = new ol.source.Vector({
      projection : 'EPSG:3857',
      format: new ol.format.GeoJSON(),
      url: 'countries.geojson'
      });
       
    var map = new ol.Map({
        target: "map",
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
          
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([2, 28.82]),
          zoom: 6
        })
      });
      map.addLayer(vectorSource);
  }

When I run the code I get the following error (debug console from Google Chrome).

**Group.js:200 Uncaught TypeError: t.getLayerStatesArray is not a function
    at Group.js:200
    at n.forEach (Collection.js:158)
    at n.getLayerStatesArray (Group.js:199)
    at n.ki (PluggableMap.js:1155)
    at n.<anonymous> (PluggableMap.js:197)**

What is wrong?

Best Answer

In map.addLayer(vectorSource) you are adding a source when addLayer expects a layer:

  map.addLayer(
    new ol.layer.Vector({
     source: vectorSource
    })
  );