【问题标题】:How to load Open layers 3 geojson vector layer with bbox?如何使用 bbox 加载 Open layers 3 geojson 矢量图层?
【发布时间】:2014-11-10 12:58:47
【问题描述】:

我正在努力构建 OL3 矢量层 BBOX 策略加载。到目前为止,我可以使用有效的 json 语法轻松加载 Geojson 文件,但这是一次性策略。我的另一种方法是使用 ol.ServerVector,据我了解,它返回带有回调的 Javascript,但我无法使其工作。

工作简单的 Geojson 层:

var vectorSource = new ol.source.GeoJSON(
({
  projection: 'EPSG:3857',
  preFeatureInsert: function(feature) {
    feature.geometry.transform('EPSG:4326', 'EPSG:3857');
  },
  url: 'geojson2.json'
}));

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

BBOX 尝试(这是在移动时返回 json,但功能未加载到地图):

    var vectorSource = new ol.source.ServerVector({
  format: new ol.format.GeoJSON(),
  loader: function(extent, resolution, projection) {
    var url = 'geojson2.php?p='+
        extent.join(',');
    $.ajax({
      url: url
    });
  },
  strategy: ol.loadingstrategy.bbox,
  projection: 'EPSG:3857',

});
// callback ?
var loadFeatures = function(response) {
  vectorSource.addFeatures(vectorSource.readFeatures(response));
};

JSON 响应示例:

{"type":"FeatureCollection","features":[
{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"label":"122.234-10/163"}},
{"type":"Feature","geometry":{"type":"Point","coordinates":[1,1],"properties":{"label":"132.222-1126"}}}
]}

【问题讨论】:

    标签: javascript json vector layer openlayers-3


    【解决方案1】:

    为了让它与最新版本的 OL3 (v3.7.0) 一起使用,我必须使用 GeoJSON 格式类阅读这些功能。

    var geoJSONFormat = new ol.format.GeoJSON();
    
    var vectorSource = new ol.source.Vector({
      loader: function(extent, resolution, projection) {
        var url = 'geojson2.php?p=' + extent.join(',');
        $.ajax({
          url: url,
          success: function(data) {
            var features = geoJSONFormat.readFeatures(data);
            vectorSource.addFeatures(features);
          }
        }); 
      },
      strategy: ol.loadingstrategy.bbox
    });
    

    【讨论】:

      【解决方案2】:

      您需要添加一个将特征添加到矢量源的 Ajax 回调:

      var vectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        loader: function(extent, resolution, projection) {
          var url = 'geojson2.php?p=' + extent.join(',');
          $.ajax({
            url: url,
            success: function(data) {
              vectorSource.addFeatures(vectorSource.readFeatures(data));
            }
          }); 
        },
        projection: 'EPSG:3857',
        strategy: ol.loadingstrategy.bbox
      });
      

      【讨论】:

      • 啊,太简单了...谢谢,我查看了错误的文档。这显然是 jquery ajax 方法。
      • @erilem 从 v3.7 开始,这仍然是首选方法吗? readFeatures 方法似乎不再存在。
      最近更新 更多