开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第1天,点击查看活动详情
使用vue3+openlayer在地图上绘制点、线、面
技术栈:vue3+openLayer
项目中接触到的openLayer,用以渲染显示功能;
仅用于使用功能,可能不会涉及太深奥的部分。以下中名词可能有不对的地方,欢迎指正。
项目一般是用获取到的坐标数据,有可能是点线面中的一种,来渲染城市中心点、街道、店铺、区域。
绘制点线面需要先引用:
Point:点LineString:线MultiLineString:多线Polygon:多边形MultiPolygon:多多边形
import { Point, LineString, MultiLineString, Polygon, MultiPolygon } from 'ol/geom'//用于绘点线面
添加图层
下面是我碰见过的几种格式的坐标数据以及使用方式:
下面出现的addressLayer是设置的图层;
设置图层
引用图层和图层样式:
import { Fill, Stroke, Style, Icon } from 'ol/style'
import VectorLayer from 'ol/layer/Vector'
通过设置图层可满足项目中对点(设置坐标点)、线样式设计、面(颜色填充),自定义图层样式。
addLayer() {
//设置图层
let VectorLayer = new VectorLayer({
lid: 'addressLayer',
source: new VectorSource(),
style: new Style({
fill: new Fill({//填充
color: 'rgba(0, 0, 0, 0.1)',
}),
stroke: new Stroke({//描边
color: 'rgba(171,37,36, 0.7)',
width: 6,
}),
image: new Icon({// 图标
anchor: [0.5, 0.96],
crossOrigin: 'anonymous',
src: require('./img/point.png'),
}),
}),
})
// 添加图层
this.map.addLayer(this.vectorLayer);
}
效果展示:
1、坐标属性加坐标点
let s1 = {
coordinates: [120.112221, 30.284268],// 经度,纬度 例: 120, 30
type: "Point"// 坐标属性
}
方法:
addFeature() {
//获取图层数组
let layers = this.map.getLayers().getArray()
//根据图层名获取图层
this.addressLayer = layers.filter((l) => l.get('lid') === 'addressLayer')
let layerSource = null
if (layers.length > 0) {
layerSource = this.addressLayer[0].getSource()
}
if (layerSource) {
//如果已有图层的话 先进行清空
layerSource.clear()
let s1 = {
coordinates: [120.112221, 30.284268],// 经度,纬度 例: 120, 30
type: "Point"
}
const feature1 = new Feature({ geometry: new Point(s1) })
layerSource.addFeature(feature1)
}
}
2、wkt格式
let s1 = 'POINT(120.22 29.7)';// 点
let s2 = 'POLYGON((121.40625 29.6875,121.375 29.6875,121.375 29.708333,121.40625 29.708333,121.40625 29.6875))';// 多边形
方法:
addFeature() {
//获取图层数组
let layers = this.map.getLayers().getArray()
//根据图层名获取图层
this.addressLayer = layers.filter((l) => l.get('lid') === 'addressLayer')
let layerSource = null
if (layers.length > 0) {
layerSource = this.addressLayer[0].getSource()
}
if (layerSource) {
//如果已有图层的话 先进行清空
layerSource.clear()
let s2 = 'POLYGON((121.40625 29.6875,121.375 29.6875,121.375 29.708333,121. 40625 29.708333,121.40625 29.6875))';
const feature2 = new WKT().readFeature(s2)
layerSource.addFeature(feature2)
}
}