二十一、openlayers官网示例Custom Controls解析——自定义控件扩展Control类

官网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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值