在vue3中重写openlayers的自定义Controls

自定义openlayers的controls
第一步:
首先创建了一个新的[类继承]了原本的Control
第二步:
给super方法的element指定一个htmlElement对象
第三步:
给element对象绑定事件

关于target的参数的传递,如果不传或者是像例子中传递target:opt_options.target,则自定义的控件被插入到如图位置

image.png

target也可以传递一个自己的指定位置,例如target:upRef.value,,
<div ref="outBtnRef" class="north-btn">

核心代码是:

 <div ref="outBtnRef" class="north-btn">
      <button  @click="handleRotateNorth">指北</button>
    </div>
let northRef = ref()
class RotateNorthControl extends Control {
  constructor(opt_options: any) {
    super({
      element: outBtnRef.value
    })
  }
}
function handleRotateNorth() {
  openlayerMap.getView().setRotation(0)
}

以下是完整代码:

<!-- eslint-disable vue/multi-word-component-names -->
// eslint-disable-next-line vue/multi-word-component-names
<template>
  <div>
    <div  ref="upRef" style="background-color: pink;width:100%;height: 20px;"></div>
    <div ref="outBtnRef" class="north-btn">
      <button  @click="handleRotateNorth">指北</button>
    </div>

    <div ref="mapRef" style="width: 512px; height: 512px" tabindex="0" class="map-container"></div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import 'ol/ol.css'
import Map from 'ol/Map.js'
import TileLayer from 'ol/layer/Tile.js'
import View from 'ol/View.js'
import { Control, defaults as defaultControls } from 'ol/control.js'
import StadiaMaps from 'ol/source/StadiaMaps'


let outBtnRef = ref()
let openlayerMap: Map
let mapRef = ref()
let upRef=ref()

const view3857 = new View({
  projection: 'EPSG:3857',
  center: [0, 0],
  zoom: 3,
  rotation: 1
})

function getStamenWatercolorSource() {
  return new StadiaMaps({
    layer: 'stamen_watercolor'
    // apiKey: 'OPTIONAL'
  })
}

function getStamenWatercolorLayer() {
  const source = getStamenWatercolorSource()
  return new TileLayer({
    source
  })
}

class RotateNorthControl extends Control {
  /**
   * @param {Object} [opt_options] Control options.
   */
  constructor(opt_options: any) {
    super({
      element: outBtnRef.value,
      //target:opt_options.target
      target:upRef.value,
      
    })
  }
}
function handleRotateNorth() {
  openlayerMap.getView().setRotation(0)
}

onMounted(() => {
  const layers = getStamenWatercolorLayer()
  openlayerMap = new Map({
    controls: defaultControls({ rotate: false }).extend([new RotateNorthControl({})]),
    layers: [layers],
    target: mapRef.value,
    view: view3857
  })
})
</script>

<style scoped>
.map-container:focus {
  outline: #4a74a8 solid 0.15em;
}
.north-btn{
  position: relative;
  float: right;
}

</style>


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容