OpenLayer自定義工具欄

因爲業務要求,去年寫過基於OpenLayer的工具欄,網上有些工具欄的文章,但是都沒什麼人提供源碼學習。

希望我的demo能幫助大家更好的理解與開發,有什麼不足請見諒,這裏說下我的基本的實現。

實現的功能

openLayer上有些例子,建議熟讀文檔後再來看本例

從左到右實現了定位,繪圖,地圖切換,撤銷最近一次繪圖,清空畫布,全屏。
如果有其他需要可以改我代碼自己添加。 github地址會在文章最後給出。

在這裏插入圖片描述

實現的方式

所有的相關文件都放在map文件夾中,
在這裏插入圖片描述
mapconfig中處理地圖的一些相關配置,類似:

// 高德地圖
const MAP3 = new layer.Tile({
  source: new source.XYZ({
    url: 'https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}'
  })
})
const mapconfig = {
  x: 114.064839,
  y: 22.548857,
  zoom: 15,
  VectorDraw,
  VectorDrawLayer,
  streetmap: streetmap,
  setDrawVectorIndex
}

map.js中構造一個class類, 提供一些地圖相關的方法供外部調用

export default class OlMap extends Map {
  // 設置父類默認值
  constructor (target) {...}
  changeDrawType (){}
  clearLastDraw () {}
}

olMap中製作工具欄,拋出組件供外部調用

<template>
	<div ref="map" id="map" :style="{width:width,height:height}">
	 <!-- 自定義工具欄 -->
	   <div class="tool-container">
	     <div class="t_close"></div>
	     <ul>
	       <li @click="changeType('Point')">
	         <div class="icon" title="定點">
	           <img src="./image/icon1.svg">
	         </div>
	       </li>
	       <li @click="changeType('Hand')">
	         <div class="icon" title="畫筆">
	           <img src="./image/icon2.svg">
	         </div>
	       </li>
	   ....
</template>
...
methods:{
	createMap (dom) {
	  this.map = new OlMap(dom)
	},
	// 改變繪圖類型
	changeType (val) {
	  this.map.changeDrawType({ type: val })
	},
}

繪圖是圓還是線段等根據傳入的類型判斷,默認是手繪

* Point:* LineString:* LinearRing:線性環
 * Polygon:多邊形
 * MultiPoint:多點
 * MultiLineString:MultiLineString
 * MultiPolygon:多多邊形
 * GeometryCollection:幾何集合
 * Circle:圈

Popover是自己封裝的一個組件提供給工具欄作爲切換的時候的下拉彈窗

在這裏插入圖片描述
單獨拿出一個功能來說,就說說撤銷上一步操作吧

// 刪除上一次處於繪畫中的上一個點
  clearLastDraw () {
    if (!this.data.draw) return
    const removeLastFeature = () => {
      const featuresArray = Config.VectorDraw.getFeatures()
      if (featuresArray.length !== 0) {
        Config.VectorDraw.removeFeature(featuresArray[featuresArray.length - 1])
      }
    }
    // 如果處於線段或多邊形繪畫中 撤銷上一個點
    if (this.data.draw.finishCoordinate_) {
      this.data.draw.removeLastPoint()
      if (!this.data.draw.finishCoordinate_) {
        removeLastFeature()
      }
    } else { // 否則取消上一次繪圖
      removeLastFeature()
    }
  }

兩種情況:
1.如果繪圖已經完成,去找所有的繪圖,從中刪除最近的一個Feature。
2.如果繪圖是多邊形繪製到一半,會根據最近點下的點位,刪除那個點位

總結:

具體的每個功能的實現請大家看源碼,每個功能都有詳細的註釋,覺得有幫助的話就給我點個star,哈哈,謝謝

github地址: https://github.com/Yukyi/olMap

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章