注册获取key和jscode
npm i @amap/amap-jsapi-loader --save
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
securityJsCode: '415e917da833efcf2d5b69f4d821784b'
}
interface Window {
_AMapSecurityConfig: {
securityJsCode: string
}
}
import AMapLoader from '@amap/amap-jsapi-loader'
onMounted(async () => {
// ... 省略 ...
AMapLoader.load({
key: '4eed3d61125c8b9c168fc22414aaef7e',
version: '2.0'
}).then((AMap) => {
// 使用 Amap 初始化地图
})
})
const map = new AMap.Map('map', {
mapStyle: 'amap://styles/whitesmoke',
zoom: 12
})
AMap.plugin('AMap.Driving', function () {
const driving = new AMap.Driving({
map: map,
showTraffic: false,
hideMarkers: true
})
if (
logistics.value?.logisticsInfo &&
logistics.value.logisticsInfo.length >= 2
) {
const list = [...logistics.value.logisticsInfo]
// 起点
const start = list.shift()
// 终点
const end = list.pop()
driving.search(
[start?.longitude, start?.latitude],//起点经纬度
[end?.longitude, end?.latitude],//终点经纬度
{ waypoints: list.map((item) => [item.longitude, item.latitude]) },//轨迹坐标点经纬度
() => {
// 规划完毕
}
)
}
})
if (
logistics.value?.logisticsInfo &&
logistics.value.logisticsInfo.length >= 2
) {
const list = [...logistics.value.logisticsInfo]
// 创建标记函数
const getMarker = (
point: Location,
image: string,
width = 25,
height = 30
) => {
const icon = new AMap.Icon({
size: new AMap.Size(width, height),
image,
imageSize: new AMap.Size(width, height)
})
const marker = new AMap.Marker({
position: [point?.longitude, point?.latitude],
icon: icon,
offset: new AMap.Pixel(-width / 2, -height)
})
return marker
}
// 起点
const start = list.shift()
const startMarker = getMarker(start!, startImg)
map.add(startMarker)
// 终点
const end = list.pop()
const endMarker = getMarker(end!, endImg)
map.add(endMarker)
driving.search(
[start?.longitude, start?.latitude],
[end?.longitude, end?.latitude],
{ waypoints: list.map((item) => [item.longitude, item.latitude]) },
() => {
// 规划完毕
// 运输位置
const curr = logistics.value?.currentLocationInfo
const currMarker = getMarker(curr!, carImg, 33, 20)
map.add(currMarker)
// 3s后定位当中间进行缩放
setTimeout(() => {
map.setFitView([currMarker])
map.setZoom(10)
}, 3000)
}
)
}