npm i @amap/amap-jsapi-loader --save
<template><div id="container"></div></template>
<script lang="ts" setup>
import { shallowRef } from "@vue/reactivity";
import { onMounted } from "vue";
import initMap from "./map";
const map = shallowRef();
onMounted(() => {
map.value = new initMap("container", () => {
map.value.getAccuratePosition();
});
});
</script>
<style lang="scss" scoped>
#container {
padding: 0px;
margin: 0px;
width: 100%;
height: 800px;
}
</style>
import AMapLoader from "@amap/amap-jsapi-loader";
interface PathInfo {
startpoint: string;
endpoint: string;
}
export default class Map {
key = "079e4f99d38e12c1f744b3897a407cc9";
code = "9ca89a8736b86ed976341a2611dbc92e";
AMap: any; //map类
map: any; // 地图实例
center: number[] | undefined; //中心点
constructor(domElement: string, callBack: Function) {
this.initMap(domElement, callBack);
}
// 初始化 https://lbs.amap.com/api/jsapi-v2/guide/abc/prepare
initMap(domElement: string, callBack: Function) {
(window as any)._AMapSecurityConfig = {
securityJsCode: this.code
};
AMapLoader.load({
key: this.key,
version: "2.0"
}).then((AMap) => {
this.AMap = AMap;
this.map = new AMap.Map(domElement, {
viewMode: "3D", //是否为3D地图模式
zoom: 10, //地图级别
center: this.center
});
callBack();
});
}
// 获取精确位置 https://lbs.amap.com/api/jsapi-v2/guide/services/geolocation
getAccuratePosition() {
this.AMap.plugin("AMap.Geolocation", () => {
const geolocation = new this.AMap.Geolocation({
enableHighAccuracy: true,
timeout: 10000,
offset: [10, 20],
zoomToAccuracy: true,
position: "RB"
});
geolocation.getCurrentPosition((status: any, result: any) => {
if (status === "complete") {
onComplete(result);
} else {
onError(result);
}
});
const onComplete = (data: any) => {
console.log(data);
};
const onError = (data: any) => {
console.log(data);
};
});
}
// 获取城市信息 https://lbs.amap.com/api/jsapi-v2/guide/services/geolocation
getCurrentCityInfo() {
this.AMap.plugin("AMap.CitySearch", () => {
const citySearch = new this.AMap.CitySearch();
citySearch.getLocalCity((status: any, result: any) => {
if (status === "complete" && result.info === "OK") {
console.log(result);
}
});
});
}
// 获取天气 https://lbs.amap.com/api/jsapi-v2/guide/services/weather
getCityWeather(cityName: string) {
this.AMap.plugin("AMap.Weather", () => {
const weather = new this.AMap.Weather();
weather.getLive(cityName, (err: any, data: any) => {
console.log(err, data);
});
});
}
// 跳转高德H5页面 https://lbs.amap.com/api/uri-api/guide/travel/route
// 微信浏览器,qq浏览器等三方浏览器可能无法唤起高德
// 如果点击返回会退出系统,将高德的页面放在iframe里面
toGaodeH5(pathInfo: PathInfo, callBack: Function) {
const { startpoint, endpoint } = pathInfo;
const url = `https://uri.amap.com/navigation?from=${startpoint},startpoint&to=${endpoint},endpoint&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=1`;
callBack(url);
}
}