Reputation: 309
I'm migrating a map applications from Openlayers 2 into ol3 and had a bbox layer which fired a request to the server when the extent changes. I use the refresh strategy (with force: true) and the server returns an array of objects I process using a custom format.
var refreshStrategy = new OpenLayers.Strategy.Refresh({
force: true
});
OpenLayers.Format.GTFS = OpenLayers.Class(OpenLayers.Format, {
read: function(body) {
var stops = JSON.parse(body), point, features = [];
for(var i=0,l=stops.length; i<l; i++) {
point = new OpenLayers.Geometry.Point(stops[i].stop_lon, stops[i].stop_lat);
features.push(new OpenLayers.Feature.Vector(point, stops[i]));
}
return features;
}
});
var layer = new OpenLayers.Layer.Vector('Stops', {
projection: new OpenLayers.Projection('EPSG:4326'),
visibility: true,
strategies: [
new OpenLayers.Strategy.BBOX({resFactor: 1.2}),
refreshStrategy
],
protocol: new OpenLayers.Protocol.HTTP({
format: new OpenLayers.Format.GTFS(),
url: '/api/v1/stops.json'
})
});
refreshStrategy.activate();
It appears ol.source.Vector
supports only a single strategy. I tried using just the bbox strategy but the feature markers flicker and data get's reloaded every time I pan
var stopFeatures = new ol.Collection();
var source = new ol.source.Vector({
features: stopFeatures,
loader: function(extent, resolution, projection) {
extent = ol.extent.applyTransform(extent, ol.proj.getTransform("EPSG:3857", "EPSG:4326"));
var url = '/api/stops.json?bbox=' + extent.join(',');
$http.get(url).then(function (res) {
var features = _.map(res.data, function (stop) {
var stopFeature = new ol.Feature(stop);
stopFeature.setGeometry(new ol.geom.Point(ol.proj.transform([stop.stop_lon,stop.stop_lat],
'EPSG:4326', 'EPSG:3857')));
return stopFeature;
});
stopFeatures.clear();
stopFeatures.extend(features);
});
},
projection: 'EPSG:4326',
strategy: ol.loadingstrategy.bbox,
});
The clearing and resetting of the feature collection feels like I'm doing something wrong and the refresh appears to be slower.
Is map.on('moveend',...
the way to go at implementing this on ol3?
Upvotes: 1
Views: 525
Reputation: 5648
You are right - you should not be calling clear()
and extend()
on the feature collection. Instead, you should have something like a unique id for each feature in your JSON. If you don't, you could use a hash created from latitude and longitude. Once you have an id, use stopFeature.setId(id)
to set the id on the feature. Then simply call source.addFeatures(features)
. The strategy will internally compare feature ids to ids of existing features, and only insert those features with ids that are not in the source already.
Upvotes: 1