I have a map with a Vector layer, containing features from a GeoJSON source:
var map = new ol.Map({
layers: [new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: new ol.source.Vector({
url: 'http://example.com:5000/geo/data/zones/1',
format: new ol.format.GeoJSON()
}),
})],
renderer: 'canvas',
target: 'map',
view: new ol.View({
center: [737514.438475665, 5864533.629390752],
zoom: 13
})
});
I have multiple URLs that returns s GeoJSON string:
http://example.com:5000/geo/data/zones/1
http://example.com:5000/geo/data/zones/2
http://example.com:5000/geo/data/zones/n
I need to be able to switch the URL of my Layer source (or fetch and display features from another URL).
I have tried to find the 'url' property on the ol.Layer.Vector instance:
l=m.getLayers().getArray()[1]
l.getProperties()
and on the ol.source.Vector instance:
s = l.getSource()
s.getProperties()
but I haven't found anything about the 'url' property.
Could you provide a way to do that ?
- is it possible to simply update the source URL (and automagically refresh the layer features) ?
- shall I remove existing features, load new features using my own logic and add the loaded ones ?
- shall I remove the whole Layer, re-create it, and re-add it ?
Best Answer
This answer by Pedro Baracho was given on StackOverflow: https://stackoverflow.com/a/31995204/1300775 (sorry for cross-posting)
You can create a new source and set it on the target layer using ol.layer.Layer.setSource.
If both layers are visible, the map will automagically refresh the features.
You can add or remove features on your Vector Layer using:
See also: ol.Feature and ol.layer.Vector.forEachFeature
You can do that using ol.Map.addLayer and ol.Map.removeLayer.
Final answer
All options listed above will switch the URL of your Layer. Each option triggers its own set of events and works with different parameters and objects. Based on my personal understanding, I would suggest:
Use option 1, if you are loading a new layer with the same properties of your old layer, but with new data.
Use option 2, if you have very few changes regarding some features on a Vector layer.
Use option 3, if you have a whole new layer, with different properties than your previous layer.