Openlayers 从变量而不是 url 加载 GEOJSON

Openlayer load GEOJSON from a variable instead of url

我有一个地图表示,我想添加一个基于 GEOJSON 的层,但我不想直接从 GEOJSON 文件中读取它,而是我有一个包含确切字符串的变量我需要的 GEOJSON 可以从变量而不是 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
    })
});

您可以从字符串中读取特征并将它们添加到源中

   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()
      })
    );

或者您可以使用数据 url 并让 OpenLayers 加载该数据

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
    })
});