OpenLayers基础操作
本文可能用到的引入:
import WKT from 'ol/format/WKT'
import GeoJSON from 'ol/format/GeoJSON'
import Style from 'ol/style/Style'
import Stroke from 'ol/style/Stroke'
import Fill from 'ol/style/Fill'
import Vector from 'ol/source/Vector'
import LayerVector from 'ol/layer/Vector'
import { getCenter } from 'ol/extent'
本文采用的API版本为:ol-6.5.0
1、创建与移除图层
使用自定义类型标识添加图层,移除标识图层,可防止removeLayer移除底图
// 创建面
createPolygon(wkt, fillColor) {
// 创建样式
const style = new Style({
stroke: new Stroke({
color: 'rgba(136,136,136,0.8)',
width: 2
}),
fill: new Fill({
color: fillColor
})
})
// 创建要素
const feature = new WKT().readFeature(wkt)
feature.setStyle(style)
// 创建数据源
const source = new Vector()
source.addFeature(feature)
// 创建图层
const layer = new LayerVector({
source: source
})
// 自定义标识类型
layer._type = 'custom'
// 添加图层
this.olMap.map.addLayer(layer)
}
removeAllLayer() {
const layers = this.olMap.map
.getLayers()
.getArray()
.slice()
for (let index = 0; index < layers.length; index++) {
const layer = layers[index]
if (layer._type === 'custom') {
this.olMap.map.removeLayer(layer)
}
}
}
2、WKT定位图层
// 设置全局变量,记录初始位置
Size = ''
zoomMap(wkt) {
const feature = new WKT().readFeature(wkt)
const view = this.olMap.map.getView()
const extent = feature.getGeometry().getExtent()
if (this.Size === '') {
this.Size = this.olMap.map.getSize()
}
this.Resolution = view.getResolutionForExtent(extent, this.Size)
view.setResolution(this.Resolution)
view.setCenter(getCenter(extent))
}
// 此方法也可实现缩放
this.olMap.map.getView().fit(extent)
注:初始记录Resolution ,为api 存在的一个问题,每次移动图层之后this.olMap.map.getSize()会发现变化,
解决方法:
1、记录第一次的,能保留移动初始的位置(如上)
2、this.olMap.map.getSize()是底图容器盒子的像素值可直接设置成固定值
[1500,780]
3、WKT转GeoJSON
实用方法
wktToGeoJSON(wkt) {
if (wkt !== '') {
const newFeature = new WKT().readFeature(wkt)
const jsonShape = new GeoJSON().writeFeature(newFeature)
return jsonShape
}
}
参考文献
官网传送门
4、 声明
1)本文来源项目实践,已经过测试,文章存在任何问题或疑问,请留言,感谢您的阅读!
2)原创不易,转载请标注来源,感谢!
3)made in wmgis