<template>
<div id="map"></div>
</template>
<script>
import "ol/ol.css";
import { Map, View, Feature } from "ol";
import XYZ from "ol/source/XYZ";
import { Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer, Tile as TileLayer } from "ol/layer";
import { Style, Icon } from "ol/style";
import Point from "ol/geom/Point";
export default {
data() {
return {
map: null,
roadmap: null,
vectorLayer: null, //创建图层
vectorSource: null, //图层数据容器
localtion: [114.028222,31.914839],
}
},
methods: {
initMap() {
let _self = this;
//线路图
this.roadmap = new TileLayer({
visible: true,
name: '电子图',
source: new XYZ({
url: 服务地址+"/tiles/ZhengZhouShi/roadmap/{z}/{x}/{y}.png",
crossOrigin: "anonymous", //离线瓦片跨域处理
}),
});
this.map = new Map({
target: "map",
layers: [this.roadmap],
view: new View({
center: this.localtion;
projection: "EPSG:4326",
zoom: 14,
minZoom: 12,
maxZoom: 17,
}),
});
// 创建图层
this.vectorLayer = new VectorLayer();
// 创建数据容器
this.vectorSource = new VectorSource();
// 把数据容器添加到图层
this.vectorLayer.setSource(this.vectorSource);
// 添加到地图上
this.map.addLayer(this.vectorLayer);
this.setPoint(this.localtion);
//获取鼠标点击的坐标点
this.map.on("singleclick", function (evt) {
const coordinate = evt.coordinate;
let longitude = coordinate[0];
let latitude = coordinate[1];
let Markers = { longitude, latitude };
_self.setPoint(Markers);
});
},
//添加定位图标
setPoint(local) {
this.pointLayer = new Feature({
name: 'point点',
geometry: new Point(local),
});
this.pointLayer.setStyle(
new Style({
image: new Icon({
src: require("@/assets/image/marker-icon.png"),
})
})
);
this.vectorSource.addFeature(this.pointLayer);
//定位过度动画
this.map.getView().animate({
center: local, // 中心点
zoom: 14, // 缩放级别
rotation: undefined, // 缩放完成view视图旋转弧度
duration: 500, // 缩放持续时间,默认不需要设置
});
}
}
};
</script>
<style scoped lang="scss">
#map{
width: 100%;
height: 800px;
}
</style>
效果图