有没有办法在第一次鼠标鼠标事件之前强制执行刚创建的Draw交互以显示自己?
我使用openlayers 4.6.5。应用程序创建ol.interaction.Draw以响应键盘事件。类型是LineString。在第一次鼠标移动之后,在鼠标位置显示预期的圆圈。我的问题是,在用户第一次移动鼠标之前,Draw交互不会显示任何内容。
交互由鼠标事件驱动,因此您需要重新运行最后一个事件。
将pointermove
事件的侦听器添加到地图并保存最后一个
var lastEvent;
map.on('pointermove', function(event){ lastEvent = event; });
然后当你添加交互时,让它来处理最后一个事件
map.addInteraction(draw);
draw.handleEvent(lastEvent);
版本4.6.4适用于我。 5秒后添加交互,然后删除,并以5和10秒的间隔添加新的交互:
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var source = new ol.source.Vector();
var vector = new ol.layer.Vector({
source: source
});
var map = new ol.Map({
layers: [raster, vector],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var draw; // global so we can remove it later
function addInteraction() {
draw = new ol.interaction.Draw({
source: source,
type: 'LineString'
});
map.addInteraction(draw);
}
var lastEvent;
map.on('pointermove', function(event){ lastEvent = event; });
var add = false;
setInterval(function(){
add = !add;
if (add) {
addInteraction();
draw.handleEvent(lastEvent);
} else {
map.removeInteraction(draw);
}
}, 5000);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/openlayers/4.6.4/ol.js"></script>
<div id="map" class="map"></div>