如何将GeoJSON导入到OpenLayers?

3
我已经尝试将以下功能和新的矢量图层添加到我的代码中。我将GeoJSON文件上传到了BPlaced账户中,以便在我的代码中链接该文件,这样正确吗? Geojson与网站具有相同的坐标系统。但是代码似乎可以工作,但是我看不到任何Geojson。 还有其他将GeoJSON嵌入OpenLayers的方法吗? 这是我的代码:
var vectorLayerJSON = new ol.layer.Vector({
  source: new ol.source.Vector({
    format: new ol.format.GeoJSON(),
    url: 'http://kristinab.bplaced.net/ALDI_LIDL_Buffer_KBS_3857.geojson'
  }),
  style: new ol.style.Style({
    image: new ol.style.Circle(({
      radius: 20,
      fill: new ol.style.Fill({
        color: '#ffff00'
      })
    }))
  })
});
1个回答

3
我相信有几种方法可以将向量(geojson)数据添加到地图中:
  1. 使用geojson文件url加载向量数据:
    var vectorLayerJSON_1 = new ol.source.Vector({
       projection : 'EPSG:3857',
       url: 'myFolder/yourFile_1.geojson',
       format: new ol.format.GeoJSON()
    });

生成矢量图层的方法,需要从geojson对象中提取。
      var geojsonObject = {
            'type': 'FeatureCollection',
            'crs': {
              'type': 'name',
              'properties': {
                'name': 'EPSG:3857'
              }
            },
            'features': [{
              'type': 'Feature',
              'geometry': {
                'type': 'Point',
                'coordinates': [0, 0]
              }
            }, {
              'type': 'Feature',
              'geometry': {
                'type': 'LineString',
                'coordinates': [[456, -256], [816, 226]]
              }...

    var vectorLayerJSON_2 = new ol.source.Vector({
            features: (new ol.format.GeoJSON()).readFeatures(geojsonObject)
          });

在OpenLayer 3示例页面上有更详细的Geojson示例(Geojson示例)

  1. 从ajax中读取矢量要素
        var vectorLayerJSON_3 = new ol.layer.Vector({
        renderMode: 'image',
        source: new ol.source.Vector({
            loader: function() {
                $.ajax({
                    type: 'GET',
                    url: 'myFolder/yourFile_2.geojson',
                    context: this
                }).done(function(data) {
                    var format = new ol.format.GeoJSON();
                    this.addFeatures(format.readFeatures(data));
                });
            }
        }),
        style: myDefinedStyle 
    });


     var map = new ol.Map({
            layers: [
              new ol.layer.Tile({
                                source: new ol.source.OSM()
                            }),
                            vectorLayerJSON_1,
                            vectorLayerJSON_2,
                            vectorLayerJSON_3  
            ],
            target: 'map',
            view: new ol.View({
              center: [0, 0],
              zoom: 2
            })
          });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接