vue 地图路线渲染

Vue 3 + TypeScript

javascript 复制代码
<template>
	<div ref="mapContainerRef" class="real-map"></div>
</template>

<script setup lang="ts">
// 下载插件 @amap/amap-jsapi-loader
import AMapLoader from '@amap/amap-jsapi-loader'
import { onBeforeUnmount, onMounted, ref, watch } from 'vue'
import * as api from '@/api'

const mapContainerRef = ref<HTMLElement | null>(null)

const amapInstance = ref<any>(null)
const routeLine = ref<any>(null)
const startMarker = ref<any>(null)
const endMarker = ref<any>(null)

onMounted(() => {
    currentOrderId.value = route.query.orderId ?? route.params.orderId ?? ''
    getdata()
})
onBeforeUnmount(() => {
    if (amapInstance.value) {
        amapInstance.value.destroy()
        amapInstance.value = null
    }
})

const getdata = () => {
//接口
    api.enterprise_orderDetail({ orderId: currentOrderId.value }).then(res => {
        complaintTag.value = res.data.complaintTag
        detail.value = res.data.order
        initMap(res.data.order, res.data)
    })
   
}
// 获取两个经纬度中间点
 const getCenterPoint = (point1: any, point2: any) => {
  // console.log(point1, point2);
  // 角度转弧度(JS 数学函数用弧度计算)
  const rad = Math.PI / 180;
  const lat1 = Number(point1.lat) * rad;
  const lng1 = Number(point1.lng) * rad;
  const lat2 = Number(point2.lat) * rad;
  const lng2 = Number(point2.lng) * rad;
  // 球面中点计算公式
  const Bx = Math.cos(lat2) * Math.cos(lng2 - lng1);
  const By = Math.cos(lat2) * Math.sin(lng2 - lng1);
  const latMid = Math.atan2(
      Math.sin(lat1) + Math.sin(lat2),
      Math.sqrt((Math.cos(lat1) + Bx) ** 2 + By ** 2)
  );
  const lngMid = lng1 + Math.atan2(By, Math.cos(lat1) + Bx);
  
  // 弧度转回角度
  return {
      lat: Number((latMid / rad).toFixed(6)),
      lng: Number((lngMid / rad).toFixed(6))
  };
}

const initMap = async (datas: any, elseData: any): Promise<void> => {
    mapLoading.value = true
    mapError.value = ''
    try {
        // await nextTick()
        if (!mapContainerRef.value) return
        const AMap = await AMapLoader.load({
            key: '', //高德key 带秘钥那个
            version: '2.0',
            plugins: ['AMap.Driving'], // 路线规划插件
        })

        let center = getCenterPoint(
            { lat: datas.arriveLatitude, lng: datas.arriveLongitude },
            { lat: datas.departLatitude, lng: datas.departLongitude }
        )
        let radiusNum = Math.abs((datas.arriveLatitude - center.lat) * 100000)
        console.log(radiusNum);
        let scale = ref(14)
        if (radiusNum < 3000) {
            scale = 14.5
        } else if (radiusNum >= 3000 && radiusNum < 6000) {
            scale = 13
        } else if (radiusNum >= 6000 && radiusNum < 9000) {
            scale = 12
        } else if (radiusNum >= 9000 && radiusNum < 12000) {
            scale = 11
        } else if (radiusNum >= 12000) {
            scale = 10
        }

        amapInstance.value = new AMap.Map(mapContainerRef.value, {
            zoom: scale,
            center: [center.lng, center.lat],
            mapStyle: 'amap://styles/whitesmoke',
            viewMode: '2D',
        })
        // var points = [];

        startMarker.value = new AMap.Marker({
            position: [datas.departLongitude, datas.departLatitude],
            content: '<div class="map-pin start">起</div>',
            offset: new AMap.Pixel(-12, -12),
        })
        endMarker.value = new AMap.Marker({
            position: [datas.arriveLongitude, datas.arriveLatitude],
            content: '<div class="map-pin end">终</div>',
            offset: new AMap.Pixel(-12, -12),
        })
        var steps = JSON.parse(datas.steps)
        // console.log(steps)
        for (let i = 0; i < steps.length; i++) {
            const poLen = steps[i].polyline.split(";");
            for (let j = 0; j < poLen.length; j++) {
                console.log()
                points.value.push(poLen[j].split(",").map(Number));
            }
        }
       
        routeLine.value = new AMap.Polyline({
            path: points.value,
            strokeColor: '#d85f3a',
            strokeWeight: 6,
            lineJoin: 'round',
            lineCap: 'round',
        })
        // if ([4, 5, 6].indexOf(datas.orderStatus) > -1) {
        //     carMarker.value = new AMap.Marker({
        //         position: [datas.driverLongitude, datas.driverLatitude],
        //         content: '<div class="map-car">🚕</div>',
        //         offset: new AMap.Pixel(-12, -16),
        //     })
        // }
        // amapInstance.value.add([routeLine.value, startMarker.value, endMarker.value, carMarker.value])
        amapInstance.value.add([routeLine.value, startMarker.value, endMarker.value])

    } catch {
        // '地图加载失败,请检查 key 或网络'
    } finally {

    }
}
</script>
相关推荐
GISer_Jing2 小时前
从“工具应用”到“系统重构”:AI时代前端研发的范式转移与哲学思辨
前端·人工智能·学习
我家媳妇儿萌哒哒2 小时前
Element ui el-dialog 在一个有滚动条的页面,打开一个弹框,完了再打开一个弹框后,滚动条可以滚动,怎么限制不能滚动。
前端·vue.js·ui
得想办法娶到那个女人2 小时前
Vite + Vue 项目打包为 Electron 桌面应用 完整指南
前端·vue.js·electron
Sailing2 小时前
🚀🚀CLI 为什么在 2025 年突然复兴?看懂 Agent、Skill、MCP、CLI 四层架构
前端·agent·ai编程
zhangrelay2 小时前
三分钟云课实践速通--概率统计--python版
linux·开发语言·笔记·python·学习·ubuntu
ZC跨境爬虫2 小时前
Apple官网复刻第二阶段day_3:(还原苹果官网iPhone顶部标准文案区块,一次编写全局复用)
前端·css·ui·html·iphone
Momo__2 小时前
CSS :has() 选择器:让父元素"看见"子元素的状态
前端·css
漫游的渔夫2 小时前
前端开发者做 RAG:别只收集点赞点踩,用 6 个字段把反馈变成优化闭环
前端·人工智能·typescript
ponponon2 小时前
openclaw 配置出错了,怎么重新再来?比如彻底卸载或者重新选一个AI模型
前端