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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值