How to load Open layers 3 geojson vector layer wit

2019-01-27 03:30发布

问题:

I am struggling with building OL3 Vector layer BBOX strategy loading. So far I can easily load Geojson file with valid json syntax, however this is one time strategy. My another approach was to use ol.ServerVector which to my understading returns Javascript with callback, but I can't make it work.

Working simple Geojson layer:

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 attempt (This is returning json while moving , however features are not loading to the map ) :

    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 response example:

{"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"}}}
]}

回答1:

You need to add an Ajax callback that adds the features to the vector source:

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


回答2:

To get this working with the newest version of OL3 (v3.7.0) I had to read the features using the GeoJSON format class.

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