<template>
<div
class="map-container"
v-loading="loading"
:style="{
width: mapWidth,
height: mapHeight,
}"
>
<div class="map-panel" ref="mapRef"></div>
<slot />
</div>
</template>
<script>
import AMapLoader from "@/plugins/amap-jsapi-loader";
export default {
name: "MapContainer",
props: {
width: {
type: String,
default: "100%",
},
height: {
type: String,
default: "600px",
},
amapKey: {
type: String,
default: "你的高德地图key",
},
zooms: {
type: Array,
default: () => [3, 18],
},
plugins: {
type: Array,
default: () => [],
},
uis: {
type: Array,
default: () => [],
},
styleId: {
type: String,
default: "你的自定义地图样式id",
// default:"darkblue"
},
viewMode: {
type: String,
default: "2D",
},
pitch: {
type: Number,
default: 60,
},
zoom: {
type: Number,
default: 12,
},
center: {
type: [Array, String],
default() {
return [115.85, 28.68];
},
},
},
data() {
return {
loading: false,
map: null,
};
},
computed: {
mapHeight() {
return isNaN(this.height) ? this.height : `${this.height}px`;
},
mapWidth() {
return isNaN(this.width) ? this.width : `${this.width}px`;
},
options() {
if (this.viewMode === "3D") {
return {
viewMode: this.viewMode,
pitch: this.pitch,
rotation: 0,
features: ["bg", "road", "point", "building"],
};
} else {
return {};
}
},
},
async created() {
window._AMapSecurityConfig = {
securityJsCode: "你的高德地图密钥",
};
await this.createMap();
},
beforeDestroy() {
if (this.map) {
this.map.destroy && this.map.destroy();
this.map = null;
}
},
methods: {
async loadMap() {
try {
this.loading = true;
const AMap = await AMapLoader.load({
key: this.amapKey, // 申请好的Web端开发者Key,首次调用 load 时必填
version: "1.4.15", // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
plugins: this.plugins, // 需要使用的的插件列表,如比例尺'AMap.Scale'等
AMapUI: {
// 是否加载 AMapUI,缺省不加载
version: "1.1", // AMapUI 缺省 1.1
plugins: this.uis, // 需要加载的 AMapUI ui插件
},
Loca: {
// 是否加载 Loca, 缺省不加载
version: "1.3.2", // Loca 版本,缺省 1.3.2
},
// host: 'https://webapi.amap.com',
});
return AMap;
} catch (e) {
console.log(e, "地图加载失败");
return undefined;
} finally {
this.loading = false;
}
},
async createMap() {
let AMap = await this.loadMap();
if (AMap) {
this.$nextTick(() => {
if (this.$refs.mapRef) {
this.map = new AMap.Map(this.$refs.mapRef, {
zoom: this.zoom, // 级别
zooms: this.zooms, // 层级范围
center: this.center, // 中心点坐标
mapStyle: `amap://styles/${this.styleId}`,
showLabel: true,
...this.options,
});
this.$emit("ready", this.map);
}
});
} else {
setTimeout(() => {
this.createMap();
}, 0);
}
},
},
};
</script>
<style lang="scss" scoped>
.map-container {
position: relative;
/deep/ .amap-logo,
/deep/ .amap-copyright {
display: none !important;
}
.map-panel {
width: 100%;
height: 100%;
}
}
</style>
高德地图组件封装
最新推荐文章于 2024-04-22 18:47:33 发布