在一个新的项目中引入高德地图,首先要下载地图的加载文件
npm i @amap/amap-jsapi-loader
然后就可以直接开始了
话不多说,直接上代码了
<template>
<div class="about">
<div class="content" id="container"></div>
<div id="panel"></div>
<div class="btnbox">
<div class="btn" @click="jump(item.value)" v-for="item in dataList" :key="item.name">{{ item.name }}</div>
</div>
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
securityJsCode: '你的秘钥',
}
const dataList = ref([
{ name: '苏州博物馆', value: [120.63,31.32] },
{ name: '尹山湖', value: [120.69,31.24] },
{ name: '同里古镇', value: [120.72,31.16] },
{ name: '甪直古镇', value: [120.87,31.27] },
])
var map = null
var driving = null
var Amap2 = null
const getMap = () => {
console.log('getMap')
// 配置高德地图的key
AMapLoader.load({
"key": "你自己的key",
"version": "1.4.15",
"plugins": [
"AMap.InfoWindow",//地图弹窗
"AMap.PlaceSearch",//地点搜索
"AMap.Geolocation",//定位到当前位置
"AMap.Geocoder",//经纬度进行逆地理编码查询
"AMap.Driving",//驾车导航
"AMap.Transfer",//公交导航
"AMap.Walking",//步行导航
"AMap.Riding",//骑行导航
]
})
.then((AMap) => {
// 创建地图实例
map = new AMap.Map('container', {
zoom: 11, // 地图显示的缩放级别
center: [120.6519, 31.3989] // 地图中心点坐标
});
// 实例化DrivingSearch
driving = new AMap.Driving({
map: map,
panel: "panel"
});
Amap2 = AMap
})
.catch(e => {
console.log(e);
});
}
const jump = (value) => {
// 根据起终点经纬度规划驾车导航路线
console.log('jump', value);
let start=[120.6519, 31.3989]
let end=value
let tu=[120.87,31.27] //途径点
driving.search(new Amap2.LngLat(start[0],start[1]), new Amap2.LngLat(end[0], end[1]),{
waypoints:[new Amap2.LngLat(tu[0], tu[1])]
}, function (status, result) {
// result即是对应的驾车导航信息
console.log(status, result);
if (status === 'complete') {
console.log('路线规划成功');
} else {
console.log('路线规划失败:' + result.info);
}
});
}
onMounted(() => {
getMap()
})
</script>
<style lang="less" scoped>
@color1: blue;
.content {
width: 100vw;
height: 600px;
background-color: @color1;
}
.btnbox {
display: flex;
width: 500px;
justify-content: space-between;
margin-top: 20px;
margin-left: 20px;
}
.btn {
width: 100px;
height: 50px;
line-height: 50px;
background-color: rgb(235, 193, 8);
text-align: center;
border-radius: 10px;
cursor: pointer;
}
#panel{
width: 400px;
height: 800px;
overflow-x: auto;
position: fixed;
right: 20px;
top: 20px;
// background-color: rgb(255, 255, 255)
}
</style>