Atlaslog
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.

Last verified 2026-11-03 · Multiple versions · Cite this page
Applies to: OpenLayers
Symptom
Checklist
  1. Compare the two layers' source objects by identity.
  2. Compare getSource().getProjection() with each view's projection code.
  3. Check whether features are shared and mutated with setStyle or setGeometry.
  4. 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
All 120 field notesChinese originalRunnable examples
English edition written for Atlaslog from the original Chinese field note. Code is unchanged and runs as-is.
Cite this page

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).