步骤思想
1、创建地图视图
2、创建矢量容器
3、创建矢量图层
4、将矢量图层添加至地图
5、监听地图点击事件
6、创建矢量点
7、设置样式
8、将矢量容器的矢量元素清空
9、再将新的矢量点add
组件代码
<template>
<div id="container">
<div id="map"
style="width: 100%; height: 100%"></div>
</div>
</template>
<script>
import 'ol/ol.css'
import { Map, View, Feature } from 'ol'
import Projection from 'ol/proj/Projection'
import { Vector as SourceVec, ImageWMS } from 'ol/source'
import { Point } from 'ol/geom'
import { Style, Icon, Text, Fill } from 'ol/style'
import { Vector as LayerVec, Image } from 'ol/layer'
export default {
data: function () {
return {
map: {},
iconVector: {},
iconLayer: {},
};
},
created () { },
mounted () {
this.initMap()
},
methods: {
initMap () {
let that = this
let mapUrl = "http://111.229.215.211:8080/geoserver/sxmap/wms"
let mapName = "sxmap:hfshape"
let myCode = "EPSG:404000"
let myUnits = 'degrees'
//wms的边界范围
let extent = [-5783.940779486906, 2420.684125662136, -3999.448596040022, 5088.623484956386]
//wms作底图
let wmsLayer = [
new Image({
source: new ImageWMS({
ratio: 1,
url: mapUrl,
params: {
'FORMAT': 'image/png',
'VERSION': '1.1.1',
"STYLES": '',
"LAYERS": mapName,
"exceptions": 'application/vnd.ogc.se_inimage',
}
})
})
];
// 坐标系
let projection = new Projection({
code: myCode,
units: myUnits,
global: false
})
//定义地图对象
that.map = new Map({
layers: wmsLayer,
target: 'map',
view: new View({
projection,
zoom: 4,
maxZoom: 20,
}),
});
// 根据范围让地图元素居中显示 重点
that.map.getView().fit(extent, that.map.getSize());
//创建矢量容器
let iconVector = new SourceVec({
features: []
})
that.iconVector = iconVector
//创建图层
let iconLayer = new LayerVec({
source: iconVector
})
that.iconLayer = iconLayer
//将图层添加到地图上
that.map.addLayer(iconLayer)
// 监听singleclick事件
that.map.on('singleclick', function (e) {
console.log("coordinate", e.coordinate)
that.drawMark(e.coordinate)
})
},
drawMark (coordinate) {
let that = this
//创建标记feature 自定义myCoordinate属性,用于获取点标记的坐标值
let iconFeature = new Feature({
geometry: new Point(coordinate),
myCoordinate: coordinate
})
//设置标记样式
let iconStyle = new Style({
image: new Icon({
src: require('@/assets/location.png'),//图标路径
anchor: [8, 22], // 默认值为图标中心
anchorXUnits: 'pixels', //锚点x值的单位
anchorYUnits: 'pixels', //锚点y值的单位
}),
text: new Text({
text: "测试文本",
fill: new Fill({
color: "#333",
}),
offsetY: 8,
}),
})
iconFeature.setStyle(iconStyle)
that.iconVector.clear()//每次先清空容器
that.iconVector.addFeature(iconFeature)//将创建好的feature放入到容器中
// 获取标记feature的坐标
let Features = that.iconVector.getFeatures()
console.log('Features', Features)
if (Features && Features.length) {
console.log(Features[0].getGeometry().flatCoordinates)
console.log(Features[0].values_.myCoordinate)
}
}
},
};
</script>
<style lang="less" scoped>
#container {
height: 800px;
}
/*隐藏ol的一些自带元素*/
.ol-attribution,
.ol-zoom {
display: none;
}
</style>