[GIS] OpenLayers 4.2 – Add a source.vector from String, not url

geojsonopenlayersvector-layer

I'm using OpenLayers 4.2.
Currently I add a source vector to a layer vector like this :

var vectorSource = new ol.source.Vector({
    url: 'http://example/carto.geojson',
    format: new ol.format.GeoJSON()
});

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

I'd like to load my source from a string.

(url = "'{"type":"FeatureCollection",
"features":[{"type":"Feature",
  "id":0,
  "geometry":{"type":"Point",
    "coordinates":[-1.68117,
    48.3717]},
  "properties":{"titre":"Nutus",
  "datedebut":"1 avril 2018",
  "datefin":"12 avril 2018",
  "lieu":"ETANG AUX MOINES"}},
{"type":"Feature",
  "id":1,
  "geometry":{"type":"Point",
    "coordinates":[-4.50069,
    48.4083]},
  "properties":{"titre":"Nutus",
  "datedebut":"1 avril 2018",
  "datefin":"12 avril 2018",
  "lieu":"BREST "}}]}"';)

Is it possible and how?

Best Answer

What about this ...

const format = new ol.format.GeoJSON();
const features = format.readFeatures(JSON.parse(`{"type":"FeatureCollection",
"features":[{"type":"Feature",
  "id":0,
  "geometry":{"type":"Point",
    "coordinates":[-1.68117,
    48.3717]},
  "properties":{"titre":"Nutus",
  "datedebut":"1 avril 2018",
  "datefin":"12 avril 2018",
  "lieu":"ETANG AUX MOINES"}},
{"type":"Feature",
  "id":1,
  "geometry":{"type":"Point",
    "coordinates":[-4.50069,
    48.4083]},
  "properties":{"titre":"Nutus",
  "datedebut":"1 avril 2018",
  "datefin":"12 avril 2018",
  "lieu":"BREST "}}]}`))

const vectorLayer = new ol.layer.Vector({
  source: new ol.source.Vector({
    features: features
  })
})
.......