微信小程序调用腾讯地图路线规划-注意点

新建mapApi.js:

复制代码
// utils/mapApi.js
const QQ_MAP_KEY = '********************'

// 获取两点之间的路线
const getRouteBetweenPoints = (from, to, mode = 'walking') => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/${mode}/`,
      data: {
        from: `${from.latitude},${from.longitude}`,
        to: `${to.latitude},${to.longitude}`,
        key: QQ_MAP_KEY
      },
      success(res) {
        if (res.data.status === 0) {
          resolve(res.data.result.routes[0])
        } else {
          reject(new Error(res.data.message))
        }
      },
      fail: reject
    })
  })
}

// 解压polyline坐标点(腾讯地图返回的是压缩数据)
const decodePolyline = (polyline) => {
  const points = []
  for (let i = 2; i < polyline.length; i++) {
    polyline[i] = polyline[i - 2] + polyline[i] / 1000000
  }
  for (let j = 0; j < polyline.length; j++) {
    points.push({
      latitude: parseFloat(polyline[j].toFixed(6)),
      longitude: parseFloat(polyline[j + 1].toFixed(6))
    })
    j++
  }
  return points
}

module.exports = {
  getRouteBetweenPoints,
  decodePolyline
}

具体页面js:

复制代码
// pages/route/route.js
const mapApi = require('../../utils/mapApi.js')

Page({
  data: {
    markers: [],
    polyline: [],
    centerLat: 0,
    centerLng: 0
  },

  async onLoad() {
    // 你的5个经纬度点
    const points = [
      { latitude: 39.9042, longitude: 116.4074, title: '起点' },
      { latitude: 39.9142, longitude: 116.4174, title: '途经点1' },
      { latitude: 39.9242, longitude: 116.4274, title: '途经点2' },
      { latitude: 39.9342, longitude: 116.4374, title: '途经点3' },
      { latitude: 39.9442, longitude: 116.4474, title: '终点' }
    ]
    
    // 添加标记点
    const markers = points.map((point, index) => ({
      id: index,
      latitude: point.latitude,
      longitude: point.longitude,
      title: point.title,
      iconPath: index === 0 ? '/images/start.png' : 
                 index === points.length - 1 ? '/images/end.png' : '/images/waypoint.png',
      width: 30,
      height: 30
    }))
    
    this.setData({ markers })
    
    // 依次获取相邻两点之间的路线
        // 依次获取相邻两点之间的路线,控制并发频率为每秒3次
        let allRoutePoints = []
    
        // 简化的并发控制实现
        const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))
        
        for (let i = 0; i < points.length - 1; i++) {
          try {
            console.log(`正在获取第 ${i+1} 段路线...`)
            
            // 每处理3个请求后等待1秒
            if (i > 0 && i % 3 === 0) {
              console.log('达到并发限制,等待1秒...')
              await delay(1000)
            }
            
            const route = await mapApi.getRouteBetweenPoints(points[i], points[i + 1], 'walking')
            const decodedPoints = mapApi.decodePolyline(route.polyline)
            allRoutePoints = allRoutePoints.concat(decodedPoints)
            console.log(`第 ${i+1} 段路线获取成功,当前总点数:${allRoutePoints.length}`)
          } catch (error) {
            console.error(`获取第 ${i+1} 段路线失败:`, error)
          }
        }
    
    
    // 配置路线
    this.setData({
      polyline: [{
        points: allRoutePoints,
        color: '#2E8B57',
        width: 5,
        borderColor: '#FFF',
        borderWidth: 1,
        arrowLine: true
      }],
      centerLat: points[0].latitude,
      centerLng: points[0].longitude
    })
  }
})

注意,由于调用api service接口有并发要求,每秒调用的次数不能超过5次,所以目前设置在每秒3次:

创建key:

相关推荐
2501_915918415 小时前
iOS性能数据监控:从概念到工具实践,让应用运行更流畅
android·macos·ios·小程序·uni-app·cocoa·iphone
silvia_Anne5 小时前
微信小程序(组件通讯和全局数据共享)
微信小程序·小程序
i220818 Faiz Ul5 小时前
个人健康系统|健康管理|基于java+Android+微信小程序的个人健康系统设计与实现(源码+数据库+文档)
android·java·vue.js·spring boot·微信小程序·毕设·个人健康系统
博客zhu虎康17 小时前
小程序:实现下拉刷新和上拉加载更多功能
小程序
2501_9159090621 小时前
全面解析前端开发中常用的浏览器调试工具及其使用场景
android·ios·小程序·https·uni-app·iphone·webview
云起SAAS1 天前
企业名片画册相册微信小程序源码 | 管理后台+后端 | 含产品展示资讯视频
微信小程序·广告联盟·企业名片画册相册微信小程序源码
王者鳜錸1 天前
企业解决方案十一-各类小程序定制开发
图像处理·人工智能·小程序·大模型·语音处理·定制开发
px不是xp1 天前
Docker部署Qdrant向量数据库,初始化向量数据库,重构RAG逻辑
数据库·docker·微信小程序·重构·qdrant
互联科技报1 天前
商城小程序选择哪家平台比较好?预算有限也能选对!
大数据·小程序
小盼江1 天前
Uniapp小程序鲜花商城推荐系统 买家卖家双端(web+uniapp)
前端·小程序·uni-app