在utils里面建立useScript.ts文件 封装高德地图key的使用
import { onMounted, onUnmounted, ref } from 'vue';
interface ScriptOptions {
src: string;
}
export function useScript(opts: ScriptOptions) {
const isLoading = ref(false);
const error = ref(false);
const success = ref(false);
let script: HTMLScriptElement;
const promise = new Promise((resolve, reject) => {
onMounted(() => {
script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function () {
isLoading.value = false;
success.value = true;
error.value = false;
resolve('');
};
script.onerror = function (err) {
isLoading.value = false;
success.value = false;
error.value = true;
reject(err);
};
script.src = opts.src;
document.head.appendChild(script);
});
});
onUnmounted(() => {
script && script.remove();
});
return {
isLoading,
error,
success,
toPromise: () => promise,
};
}
在需要使用的组件里面进行调用
<template>
<!-- new 地图 -->
<div id="container1" ref="wrapRef"></div>
</template>
<script lang="ts" setup>
import { ref, nextTick, unref, watch, computed } from "vue";
import { useScript } from "../../../utils/useScript";
const A_MAP_URL =
"https://webapi.amap.com/maps?v=1.4.15&key=你的key=AMap.MarkerClusterer";
const wrapRef = ref<HTMLDivElement | null>(null);
const { toPromise } = useScript({ src: A_MAP_URL });
initMap();
async function initMap() {
await toPromise();
await nextTick();
const wrapEl = unref(wrapRef);
const AMap = (window as any).AMap;
// 创建地图实例
var map = new AMap.Map(wrapEl, {
zoom: 25, //初始化地图层级
center: [经度, 纬度],
// resizeEnable: true,
viewMode: "3D",
pitch: 60,
});
}
这样高德地图初始化就完成了