Can I drag the map with ctrl in Openlayers3?

╄→尐↘猪︶ㄣ 提交于 2021-02-10 05:59:25

问题


Exist a way to drag the map when I hold down the Ctrl (control) key?

Normally to drag the map is necessary just hold the left mouse button and move on the map, but I need to drag the map without hold the left mouse button but with the ctrl button. Is possibile?


回答1:


There is indeed a way to only allow panning while holding ctrl-key. A fully working example can be found in this fiddle: https://jsfiddle.net/mnpq3ufe/

For it to work, you have to disable the existing dragPan interaction in your map init to override/re-add it later on:

interactions: ol.interaction.defaults({
    dragPan: false
})

After that you can create your new customised interaction, which just triggers while ctrl key is pressed, for this we use condition, for more information about conditions and its possibilities you can head over to the OpenLayers APIdocs:

map.addInteraction(new ol.interaction.DragPan({
  condition: function(event) {
    return event.originalEvent.ctrlKey
  }
}));

EDIT:

This is just a proof of concept yet and is not fully working, since it snaps into the wrong place when initially starting the drag. Unfortunately I have no time currently to figure everything out right now, but it could probably still help you to get started. Here is the fiddle: https://jsfiddle.net/mnpq3ufe/5/ Basically I am using the pointermove event to recenter the map each time the cursor is moved while holding the ctrl-key:

map.on('pointermove', function(event){
    if(event.originalEvent.ctrlKey){
    var pixelCenter = [map.coordinateToPixelTransform_[4], 
        map.coordinateToPixelTransform_[5]];
    var movedPixels = [pixelCenter[0]-event.pixel[0],
        pixelCenter[1]-event.pixel[1]];
    map.getView().setCenter(map.getCoordinateFromPixel(movedPixels));
  }
});


来源:https://stackoverflow.com/questions/39800406/can-i-drag-the-map-with-ctrl-in-openlayers3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!