Search code examples
javascriptmapsopenlayersgeojson

Openlayer load GEOJSON from a variable instead of url


I've a map rapresentation, I want to add a layer based on a GEOJSON, but I don't want to read it directly from a GEOJSON file, instead I've a variable that contain the exact string of GEOJSON that I require, is possible to load it from a variable instead of an url?

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        }),
        new ol.layer.Vector({
                  title: 'bikesRented',
                  source: new ol.source.Vector({
                     url: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                     format: new ol.format.GeoJSON()
                  }),
                  style: bikeStyle2
        })
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([11.341868,44.494949]),
        zoom: 14
    })
});

Solution

  • You could read the features from your string and add them to the source

       var source = new ol.source.Vector();
       var map = new ol.Map({
            target: 'map',
            layers: [
                new ol.layer.Tile({
                    source: new ol.source.OSM()
                }),
                new ol.layer.Vector({
                          title: 'bikesRented',
                          source: source,
                          style: bikeStyle2
                })
            ],
            view: new ol.View({
                center: ol.proj.fromLonLat([11.341868,44.494949]),
                zoom: 14
            })
        });
        source.addFeatures(
          new ol.format.GeoJSON().readFeatures(geojsonstring, {
            dataProjection: 'EPSG:4326',
            featureProjection: map.getView().getProjection()
          })
        );
    

    or you could use a data url and let OpenLayers load that

    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM()
            }),
            new ol.layer.Vector({
                      title: 'bikesRented',
                      source: new ol.source.Vector({
                         url: 'data:,' + encodeURIComponent(geojsonstring),
                         format: new ol.format.GeoJSON()
                      }),
                      style: bikeStyle2
            })
        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([11.341868,44.494949]),
            zoom: 14
        })
    });