【uniapp】地图路线轨迹,路线规划,兼容H5与APP端!

张开发
2026/4/16 14:06:22 15 分钟阅读

分享文章

【uniapp】地图路线轨迹,路线规划,兼容H5与APP端!
1、介绍与使用介绍地图路线规划调用高德api自动连线只需申请高德web服务即可只需传key起点终点就可实现自动连线可根据需求自行调整。导入使用插件地址uni-app项目引入即可使用支持 android 、ios 和 h5。2、代码示例template view classcontainer map idmap :latitudelatitude :longitudelongitude :markersmarkers :polylinepolyline :style{width: 100%,height: 100vh} /map /view /template script import { calculateDrivingRoute } from /js_sdk/y-mapservice/mapservice.js; export default { data() { return { latitude: 39.908823, // 默认纬度北京 longitude: 116.397470, // 默认经度 //地图 mapContext: undefined, mapPlus: undefined, //标记 markers: [], //路线 polyline: [], //起点 startLon: 0, startLat: 0, //终点 endLon: 0, endLat: 0 } }, onLoad(opt) { // 可根据自己需求获取接口获取/定位获取 this.startLon opt.startLon; this.startLat opt.startLat; this.endLon opt.endLon; this.endLat opt.endLat; }, onReady() { this.mapContext uni.createMapContext(map, this); this.mapPlus this.mapContext.$getAppMap(); this.refreshMap(); }, methods: { refreshMap() { // 定位到地图中间位置 this.mapContext.moveToLocation({ latitude: this.startLat, longitude: this.startLon }); // 添加标记 this.markers [{ id: 0, latitude: this.startLat, longitude: this.startLon, iconPath: /static/index/map-ta.png, // 标记图标 }, { id: 1, latitude: this.endLat, longitude: this.endLon, iconPath: /static/index/map-wo.png, // 标记图标 } ]; // 计算并显示路线 this.calculateRoute(); }, async calculateRoute(){ try { console.log(开始计算路线); //填写高德开发者申请的《web服务》的 key const apiKey ; const path await calculateDrivingRoute( apiKey, parseFloat(this.startLon), parseFloat(this.startLat), parseFloat(this.endLon), parseFloat(this.endLat), ); // 设置路线 this.polyline [{ points: path, color: #4dbe7c, width: 10, arrowLine: true }]; console.log(路线已设置到地图); } catch (error) { console.error(路线计算失败:, error); // 失败时不显示路线 this.polyline []; } } }, } /script3、效果图

更多文章