首先吐槽一下,網上的資源很多,但是對口的卻很少。
控制openlayer地圖,禁止使用鼠標滑輪滾動進行縮放地圖。根據版本不同,使用的方法也不同。
我現在使用的openlayer3.0版本,使用方式一能解決我的問題。分享下面方式二和方式三方法,供不同版本的小朋友參考。
方式一:
直接說解決方法:
以添加interactions的方式實現禁用鼠標滑輪滾動縮放地圖效果(open layer3.0以上版本)
在map對象裏添加interactions的設置:
interactions: ol.interaction.defaults({
doubleClickZoom: false,// 取消雙擊放大功能交互
mouseWheelZoom: false, // 取消滾動鼠標中間的滑輪交互
shiftDragZoom: false, // 取消shift+wheel左鍵拖動交互
})
代碼如下:
// 我們需要一個vector的layer來放置圖標
var layer = new ol.layer.Vector({
source : new ol.source.Vector()
});
var map = new ol.Map({
layers : [ new ol.layer.Tile({
// 加載互聯網地圖
source : new ol.source.OSM()
}),
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'EPSG:4326',
url: "XXXXXX"
})
}),layer ],
target : id,
view : new ol.View({
projection : 'EPSG:4326',
center : [ 117.57,33.27 ],
zoom : 9.5,
}),
interactions: ol.interaction.defaults({
doubleClickZoom: false,// 取消雙擊放大功能交互
mouseWheelZoom: false, // 取消滾動鼠標中間的滑輪交互
shiftDragZoom: false, // 取消shift+wheel左鍵拖動交互
})
});
其中mouseWheelZoom: false實現禁用鼠標滑輪縮放地圖;
doubleClickZoom: false實現禁用鼠標點擊(包含雙擊)放大地圖;
shiftDragZoom: false實現禁用shift+wheel左鍵拖動地圖;
方式二:
最開始使用的方式,當時不知道使用的openlayer是哪一個版本,但肯定不是3.0以上的。我使用控制最大和最小縮放值等於當前地圖縮放值。達到禁止使用鼠標滑輪滾動進行縮放地圖的目的。
zoom : 9.5,
minZoom: 9.5,
maxZoom: 9.5,
// 我們需要一個vector的layer來放置圖標
var layer = new ol.layer.Vector({
source : new ol.source.Vector()
});
var map = new ol.Map({
layers : [ new ol.layer.Tile({
// 加載互聯網地圖
source : new ol.source.OSM()
}),
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'EPSG:4326',
url: "xxxxxx"
})
}),layer ],
target : id,
view : new ol.View({
projection : 'EPSG:4326',
center : [ 117.57,33.27 ],
zoom : 9.5,
minZoom: 9.5,
maxZoom: 9.5,
})
});
也可以在map對象外,設置minZoom,maxZoom.如下:
var map = new ol.Map({
layers : [ new ol.layer.Tile({
// 加載互聯網地圖
source : new ol.source.OSM()
}),
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'EPSG:4326', url:'xxxxxx,
})
}),layer ],
target : id,
view : new ol.View({
projection : 'EPSG:4326',
center : [ 117.57,33.27 ],
zoom : 9.5
})
});
map.getView().setMinZoom(9.5);
map.getView().setMaxZoom(9.5);
方式三:
添加control代碼,設置zoomWheelEnabled爲false取消鼠標縮放地圖。也就是滾動鼠標的滾輪地圖沒有響應事件,只能用鼠標平移地圖。(網上查找的)
controls: [
new OpenLayers.Control.Navigation({ 'zoomWheelEnabled': false }),
new OpenLayers.Control.MousePosition(),
new OpenLayers.Control.Zoom()
]
但是我這裏使用的時候出現木有Navigation方法。應該是不符合我的當前3.0以上的版本。有需要的小朋友可以參考下
var map, layer;
function init(){
map = new OpenLayers.Map('map',{
controls: [
new OpenLayers.Control.Navigation({ 'zoomWheelEnabled': false }),
new OpenLayers.Control.MousePosition(),
new OpenLayers.Control.Zoom()
]
}
);
layer = new OpenLayers.Layer.OSM("Simple OSM Map");
map.addLayer(layer);
map.setCenter(
new OpenLayers.LonLat(-71.147, 42.472).transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
), 12
);
}
以上是我總結的方式,大家可以參考和談論,有不正確的地方還望訂正。