<template>
<div id="Gmaps" ref="Gmaps" tabindex="1"></div>
</template>
<style scoped>
#Gmaps {
width: 100%;
height: 100%;
}
</style>
<script>
/**
* moveEvent 地图的移动事件
* clickEvent 地图自定义点击事件
* getMap 挂载到实例的方法,获取地图实例
* mapType 平面图地址中文 planeC 卫星中文 satelliteE 默认平面图中文
*/
// 谷歌地图
import "ol/ol.css";
import { Map, View } from "ol";
import { unByKey } from "ol/Observable";
import { fromLonLat } from "ol/proj";
//配置方法
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { debounceM } from "@/utils/debounceAndthrottle";
export default {
name: "MapGoogle",
props: {
mapType:{
type:String
},
view:Object,
clickEvent:Function,
moveEvent:Function
}, //定义一个options属性用于接收外部传递给级联组件的数据,即选择项列表
// 定义数组
data() {
return {
click: null,
move: null,
// 地图对象
map: null,
iniMap: {
// 瓦片
layers: new TileLayer({
source: new XYZ({
crossOrigin: "anonymous",
url:
"http://mt2.google.cn/vt/lyrs=m&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G" //平面图地址中文
})
}),
// 中心点配置 坐标新
view: this.view
? this.layer
: {
projection: "EPSG:3857", //使用这个坐标系 纬度:34.27
center: fromLonLat([10.161290322580605, 30.65599910455336]), //深圳
zoom: 0,
minZoom: 0,
maxZoom: 18
// extent: [-572513.341856, 5211017.966314,916327.095083, 6636950.728974]
} // 初始化设置 坐标系 等
}
};
},
// mixins: [echartMixins],
watch: {
mapType: function(newVal) {
if (newVal) {
this.setLayer(newVal);
}
}
},
// 组件离开触发事件
beforeDestroy() {
//事件解绑
unByKey(this.click);
unByKey(this.move);
},
// 初始 调用接口api
created() {},
// 节点渲染完成 初始
mounted() {
this.initials();
var _this = this;
if (this.clickEvent) {
this.click = this.map.on("click", function(e) {
_this.clickEvent(e);
});
}
if (this.moveEvent) {
this.move = this.map.on(
"moveend",
debounceM(function(e) {
_this.moveEvent(e);
}, 800)
);
}
},
// 方法
methods: {
//抛出获取地图实例方法
getMap() {
return this.map;
},
// 初始化
initials() {
this.map = new Map({
target: this.$refs.Gmaps,
layers: [this.iniMap.layers],
view: new View(this.iniMap.view)
});
},
//切换图层源实现
setLayer(mapType) {
switch (mapType) {
case "planeC":
let planeC = new XYZ({
crossOrigin: "anonymous",
url:
"http://mt2.google.cn/vt/lyrs=m&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G" //平面图地址中文
});
let baseLayer1 = this.map.getLayers().item(0);
baseLayer1.setSource(planeC);
break;
case "satelliteE":
let satelliteE = new XYZ({
crossOrigin: "anonymous",
url:
"http://mt2.google.cn/vt/lyrs=y&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G" //卫星图地址中文
});
let baseLayer2 = this.map.getLayers().item(0);
baseLayer2.setSource(satelliteE);
break;
default:
this.$message("该地图类型不存在");
}
}
}
};
</script>
思路:
- 主要是封装的干干净净便于自己用起来方便。
- 事件方法是传进来的。
- getMap 挂载到实例的方法,获取地图实例,所有图层操作都出去执行,就一个底图。