2017-08-23 41 views
0

我在具有多个特征的矢量图层上启用了修改交互。将功能移到新位置可以很好地工作。但是,如果在同一个坐标上有更多的特征,那么所有的特征都会同时移动。 See example on codepenOpenlayers 4 - 在同一坐标下修改交互和多个特征

var raster = new ol.layer.Tile({ 
    source: new ol.source.OSM() 
    }); 

var data = new ol.Collection(); 

    data.push(new ol.Feature({ 
    geometry: new ol.geom.Point([0, 0]) 
    })); 

    var f = new ol.Feature({ 
    geometry: new ol.geom.Point([0, 0]) 
    }); 
    f.setStyle(new ol.style.Style({ 
       image: new ol.style.Circle({ 
        radius: 10, 
        fill: new ol.style.Fill({ 
         color: [255, 255, 255, 0.5] 
        }), 
        zIndex: Infinity 
       }), 
      })); 

    data.push(f); 

    var vector = new ol.layer.Vector({ 
    source: new ol.source.Vector({ 
     features: data 
    }) 
    }); 


    var modify = new ol.interaction.Modify({ 
    features: data 
    }); 

    var map = new ol.Map({ 
    interactions: ol.interaction.defaults().extend([modify]), 
    layers: [raster, vector], 
    target: 'map', 
    view: new ol.View({ 
     center: [0, 0], 
     zoom: 12 
    }) 
    }); 

有没有办法避免这种情况?我发现的唯一的解决方案是:

  1. 我有一个选择互为作用,选择功能
  2. 使用翻译互动移动的特点之一

  1. 在指针移动事件并检测一个或多个特征是否在坐标上,然后选择其中一个
  2. 添加所选功能以修改要素图层并移动它

还有其他方法吗?

Regrads RM

+0

您已有2种解决方案。您寻找其他解决方案的原因有哪些? –

+0

第一个解决方案需要额外的点击(选择点击),我想避免。当从一层到另一层移动特征时,secound需要进行bookeping,这使得代码更加复杂,我希望我能保持代码简单。这就是我寻找其他解决方案的原因。 – user7064696

回答

0

还有另一种方式。您可以在地图上注册一个'pointermove'处理程序,在该处理程序中获取最上面的功能,并将其设置为修改交互所在源的唯一功能。完整示例请参见https://codepen.io/ahocevar/pen/YxjyRd

除了在代码中,您将修改交互连接到源代替集合,并且该源(modifySource)与矢量图层的源分离并且最初为空。在pointermove处理程序中,添加只是一个单一的功能,将这些资料来源:

function pointermove(e) { 
    if (e.dragging) { 
    return; 
    } 
    var features = map.getFeaturesAtPixel(e.pixel, { 
    layerFilter: function(l) { 
     return l == vector; 
    } 
    }); 
    if (features && features[0] != modifySource.getFeatures()[0]) { 
    modifySource.clear(); 
    modifySource.addFeature(features[0]); 
    } 
} 
map.on("pointermove", pointermove); 

还要注意的是,修改交互添加到地图之前,该处理程序必须进行登记。

+0

嗨ahocevar 谢谢你的答案。我得到它的工作。 不允许更改modifystart事件中的要素样式吗? 我得到了与[链接](https://github.com/openlayers/openlayers/issues/6310)相同的错误,但是如果我在下面这样的更改事件中首先更改样式,它会起作用: modify.on("modifystart', function(e) { \t foreach(e.features, function(elem, ...) { \t \t elem.once("change", function (event) { \t \t \t elem.target.setStyle(...) \t \t } \t } }) 如果我没有 modify.on(“modifystart”,函数(E){ \t e.features [0] .setStyle(...) }) 我得到了错误。任何想法,为什么? – user7064696

相关问题