[GIS] OpenLayers 3, problem with GeoJSON file

coordinate systemgeojsonopenlayers

I have two layers:

var layer = new ol.layer.Tile({source: new ol.source.OSM()});

and

var layer_g=new ol.layer.Vector({
    projection : 'EPSG:4326',
    style: new ol.style.Style(
          {
              fill: new ol.style.Fill({color: [0, 255, 0, 0.2]}),
              stroke: new ol.style.Stroke({color: 'black', opacity: 0.1})

          }
            ),
    source: new ol.source.GeoJSON({
    url: 'file.geojson',
    projection : 'EPSG:3857'
    })
  });

Where the file.geojson is:

{
  "type": "LineString",
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
    }
  },
  "coordinates":
  [
[21.919146, 51.962142]
.....
,[21.955264, 51.955445]
,[21.955894, 51.955762]
,[21.956169, 51.955924]
,[21.957933, 51.956962]
  ],  "properties": {
    "distance": "9.783024",
    "description": "To enable simple instructions add: 'instructions=1' as parameter to the URL",
    "traveltime": "653"
    }
}

I add these two layers to map:

var map = new ol.Map({
  layers: [layer,w_gminy],
  target: document.getElementById('map'),
  view: view
});

But only OSM layer is visible.

Is the problem in a structure of the GeoJSON file?

Best Answer

Update your layer_g code to:

var layer_g = new ol.layer.Vector({
  style: new ol.style.Style({
    fill: new ol.style.Fill({color: [0, 255, 0, 0.2]}),
    stroke: new ol.style.Stroke({color: 'black', opacity: 0.1})
  }),
  source: new ol.source.Vector({
    url: 'file.geojson',
    format: new ol.format.GeoJSON()
  })
});

Note, ol.format.GeoJSON() is valid only since OL v3.5.0 - see changelog.