官网demo地址:
Custom Controls
这个示例讲的是如何自定义控件
首先创建了一个新的类继承了原本的Control,新增了一个button元素,然后调用了super方法将参数传给了父类。
const button = document.createElement("button");
button.innerHTML = "N";
const element = document.createElement("div");
element.className = "rotate-north ol-unselectable ol-control";
element.appendChild(button);
然后调了super方法将参数传递给父类
super({
element: element,
target: options.target,
});
可以在node_moudles里面找到Control类的源码,看到父类需要的参数。
在点击事件里调用了openlayers的setRotation()方法控制视图倾斜角度。
button.addEventListener(
"click",
this.handleRotateNorth.bind(this),
false
);
handleRotateNorth() {
this.getMap().getView().setRotation(0);
}
如果style里面设置了scoped,样式代码这里需要使用样式穿透,否则不会生效。
::v-deep #map {
.rotate-north {
top: 65px;
left: 0.5em;
}
.ol-touch .rotate-north {
top: 80px;
}
}
完整代码:
<template>
<div class="box">
<h1>自定义控件</h1>
<div id="map"></div>
</div>
</template>
<script>
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/Tile.js";
import View from "ol/View.js";
import { Control, defaults as defaultControls } from "ol/control.js";
export default {
name: "",
components: {},
data() {
return {
map: null,
};
},
computed: {},
created() {},
mounted() {
class RotateNorthControl extends Control {
/**
* @param {Object} [opt_options] Control options.
*/
constructor(opt_options) {
const options = opt_options || {};
const button = document.createElement("button");
button.innerHTML = "N";
const element = document.createElement("div");
element.className = "rotate-north ol-unselectable ol-control";
element.appendChild(button);
super({
element: element,
target: options.target,
});
button.addEventListener(
"click",
this.handleRotateNorth.bind(this),
false
);
}
handleRotateNorth() {
this.getMap().getView().setRotation(0);
}
}
this.map = new Map({
controls: defaultControls().extend([new RotateNorthControl()]),
layers: [
new TileLayer({
source: new OSM(),
}),
],
target: "map",
view: new View({
center: [0, 0],
zoom: 3,
rotation: 1,
}),
});
},
methods: {
},
};
</script>
<style lang="scss" scoped>
#map {
width: 100%;
height: 500px;
}
.box {
height: 100%;
}
::v-deep #map {
.rotate-north {
top: 65px;
left: 0.5em;
}
.ol-touch .rotate-north {
top: 80px;
}
}
</style>