因为业务要求,去年写过基于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