如果光标与其他对象对齐,则更改绘制叠加层的样式

Change the style of the draw overlay, if the cursor is snapped an other object

我有一个绘图交互来绘制点。仅当其他源的特征边界被捕捉时才允许绘制这些点。现在,如果其他特征边界被折断,叠加特征必须改变自己的样式。

var snapCondition = function(evt){
    var features = [];
    mapEntry.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
        if(layer != null && layer.get('name') === 'specialLayerName') {
            features.push(feature);
        }
    });
    if(features.length  === 1 ) {
        return checkBoundary(features[0], evt.coordinate);
    } else {
        return false;
    };
};

var checkBoundary = function(feature, coords) {
    var geom = feature.getGeometry();
    var closestPoint = geom.getClosestPoint(coords);
    console.log(closestPoint);
    console.log(coords)
    if((closestPoint[0] === coords[0]) && (closestPoint[1] === coords[1])) {
        return true;
    }
    return false;
} 
var drawBuildingEntry = new ol.interaction.Draw({
  source: buildingEntrySource,
  type: 'Point',
  condition: snapCondition,
  style: new ol.style.Style({
    image: new ol.style.Circle({
      radius: 7,
      fill: new ol.style.Fill({
        color: entryDrawColor,
      }),
      stroke: new ol.style.Stroke({
        color: 'white',
        width: 3
      })
    })
  })
});

上面的代码可以正常工作,但我通过更改样式遇到了问题。我测试了以下代码:

 mapEntry.on("pointermove", function (event) {
    var features = [];
    mapEntry.forEachFeatureAtPixel(event.pixel, function(feature, layer) {
        if(layer != null && layer.get('name') === 'specialLayerName') {
            features.push(feature);
        }
    });
    if(features.length  === 1 ) {
        console.log(checkBoundary(features[0], event.coordinate));
        if(checkBoundary(features[0], event.coordinate) === true) {
            entryDrawColor = '#40FF00'
        } else { 
            entryDrawColor = '#FF0000'; 
        };
    } else {
        entryDrawColor = '#FF0000'; 
    };});

checkBoundary的console.log甚至是false,因为事件坐标,是叠加元素被捕捉前的坐标。 最好的祝福 蒂姆

捕捉交互不会改变指针位置,但它会改变向绘图交互报告的内容,因此您可能需要在绘图的样式函数中进行测试

  style: function(feature) {
    var entryDrawColor = '#FF0000';
    var geometry = feature.getGeometry();
    if (geometry.getType() = 'Point') {
      var coordinates = geometry.getCoordinates();
      var pixel = getPixelFromCoordinate(coordinate);

      ...

    }
    return new ol.style.Style({
      image: new ol.style.Circle({
        radius: 7,
        fill: new ol.style.Fill({
          color: entryDrawColor,
        }),
        stroke: new ol.style.Stroke({
          color: 'white',
          width: 3
        })
      })
    })
  }