Atlaslog / Field Notes / OpenLayers layers
Field note · OpenLayers layers
Two layers sharing one VectorSource clear each other
Quick answer
The same VectorSource instance was passed to two VectorLayers, so source.clear() in the main view also empties the comparison view. The source owns the features and their projection, and the layers merely observe that data.
Symptom
- layerA.getSource() === layerB.getSource() evaluates to true.
- Clearing the selected-stations layer in the main map removes the same points from the side-by-side view.
- When the two maps use different view projections, the second layer's features sit offset by hundreds of metres.
Checklist
- Compare the two layers' source objects by identity.
- Compare getSource().getProjection() with each view's projection code.
- Check whether features are shared and mutated with setStyle or setGeometry.
- Check whether the comparison map uses a different EPSG code.
Fix
Give each layer its own ol.source.Vector built from cloned features (f.clone()) or re-read with geoJsonFormat.readFeatures using dataProjection EPSG:4326 and the target featureProjection.
Code
console.log(layerA.getSource() === layerB.getSource()); // true,就是问题所在
console.log(layerA.getSource().getProjection());
console.log(mapA.getView().getProjection().getCode());
console.log(mapB.getView().getProjection().getCode());var featuresA = sourceA.getFeatures();
var featuresB = featuresA.map(function (f) {
return f.clone();
});
var sourceB = new ol.source.Vector({ features: featuresB });
var layerB = new ol.layer.Vector({ source: sourceB });
Watch out
- Shallow-copying the source object still shares the feature array and the pollution persists.
- Sharing one source across maps with different projections makes the offset look like a coordinate error.
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Atlaslog (2026). Two layers sharing one VectorSource clear each other. https://www.jingweizhi.com/en/cookbook/ol-source-reuse-pollution.html (accessed 2026-11-03).