環境vue3.0項目
最初是以npm i ol -s方式安裝的ol,import方式導入引用,但是實際使用的時候一直報ol is not defined,最后選擇在HTML以script標簽引入ol,如下
<link rel="stylesheet" href="<%= BASE_URL %>./css/gr-ol.css" type="text/css">
<script src="<%= BASE_URL %>./js/gr-ol.js" type="text/javascript"></script>
然后在src內的js文件就可以直接使用ol了,要實現框選放縮,要使用ol庫里面的DragZoom控件,實例化一個DragZoom對象,添加到地圖對象(這里是kpst)里面,原本從ol庫引入的Map是帶有DragZoom的,但是改變里面condition 的name從默認的‘shiftKeyOnly’到‘always’還沒有找到方法,就重新實例化了一個DragZoom添加到現有地圖
在map組件的js文件內添加控件
import { Map, View } from 'ol';
import DragZoom from 'ol/interaction/DragZoom'
kpst._this = new Map(_op)
// 為了改變DragZoom的內容,重新實例化一個控件
var dragZoom = new DragZoom({
condition: ol.events.condition.always,
out: true, // 此處為設置拉框完成時放大還是縮小 true縮小
});
// 默認控件不激活狀態
dragZoom.setActive(false);
// 將控件添加到地圖
kpst._this.addInteraction(dragZoom);
點擊特定按鈕激活控件
// 獲取拉框控件DragZoom進行引用
var dragzoom = me.map._this.interactions.getArray()[8]
// 獲取地圖容器dom
var map_container = document.querySelector("#map_container")
// 綁定放大縮小按鈕事件
if (data.name == "拉框放大" || data.name == "拉框縮小") {
// 設置鼠標樣式為十字瞄准線
map_container.style.cursor = "crosshair";
// 激活拉框控件DragZoom
dragzoom.setActive(true)
if (data.name == "拉框放大") {
// 設置拉框放大
dragzoom.out_ = false;
} else {
// 設置拉框縮小
dragzoom.out_ = true;
}
} else {
// 禁用DragZoom控件
dragzoom.setActive(false);
map_container.style.cursor = "default";
}