/main.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "@/router";
import VueAMap, { initAMapApiLoader } from "@vuemap/vue-amap";
import "@vuemap/vue-amap/dist/style.css";
import "./styles/index.scss";
import "amfe-flexible";
initAMapApiLoader({
key: "你的Key",
plugins: [
"AMap.Autocomplete",
"AMap.PlaceSearch",
"AMap.Scale",
"AMap.OverView",
"AMap.ToolBar",
"AMap.MapType",
"AMap.PolyEditor",
"AMap.CircleEditor",
"AMap.Geocoder",
"AMap.Geolocation"
],
});
createApp(App).use(VueAMap).use(router).mount("#app");
views/Map.vue
<template>
<div class="map">
<el-amap ref="map" :center="center" :zoom="zoom" @init="init" />
</div>
</template>
<script lang="ts" setup>
import { ref, reactive, shallowRef } from "vue";
/** 地图实例 (shallowRef:如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换) */
const myMap = shallowRef(null);
/** 地图中心点(默认) */
const center = reactive([121.59996, 31.197646]);
/** 地图缩放级别(默认) */
const zoom = ref(15);
const init = (map: any) => {
const AMap = (window as any).AMap;
myMap.value = map;
getUserPosition(AMap);
};
/** 添加地图标记点 */
const addMarker = (AMap: any) => {
const marker = new AMap.Marker({
position: center,
});
(myMap.value as any).add(marker);
};
/** 高德地图获取当前用户位置 */
const getUserPosition = (AMap: any) => {
console.log("获取位置中...");
AMap.plugin("AMap.Geolocation", function () {
//异步加载插件
const Geolocation = new AMap.Geolocation({
// 是否使用高精度定位,默认:true
enableHighAccuracy: true,
// 设置定位超时时间,默认:无穷大
timeout: 6000,
// 定位按钮的停靠位置的偏移量
offset: [10, 20],
// 定位成功后调整地图视野范围使定位位置及精度范围视野内可见,默认:false
zoomToAccuracy: true,
// 定位按钮的排放位置, RB表示右下
position: "RB",
});
Geolocation.getCurrentPosition((status: any, result: any) => {
if (status == "complete") {
onComplete(result);
} else {
onError(result);
}
});
function onComplete(res: any) {
console.log(`获取位置成功:`, res);
let { position } = res;
center[0] = position.lng;
center[1] = position.lat;
addMarker(AMap);
getAdd();
}
function onError(err: any) {
console.log(`获取位置失败:`, err);
}
});
};
/** 地图加载完成后 (根据经纬度获取地址) */
const getAdd = () => {
const AMap = (window as any).AMap;
const geocoder = new AMap.Geocoder({
radius: 1000,
extensions: "all",
});
const [lng, lat] = center;
geocoder.getAddress([lng, lat], function (status: any, result: any) {
if (status === "complete" && result.info === "OK") {
console.log(result, "result");
if (result && result.regeocode) {
console.log(
`result.regeocode.formattedAddress:`,
result.regeocode.formattedAddress
);
}
}
});
};
</script>
<style lang="scss" scoped>
.map {
width: 100vw;
height: 100vh;
}
</style>