微信小程序 高德地图路线规划实现过程详解

yizhihongxing

下面我将针对“微信小程序 高德地图路线规划实现过程详解”给出完整攻略。

1. 准备工作

在进行微信小程序中的路线规划实现前,需要先前往高德开放平台进行申请并获取到 Web API Key,之后根据所需进行接口授权,获取相关权限。之后需要创建微信小程序,并获取到AppId,最后在 小程序后台-开发-开发设置 中将域名加入到 request 合法域名中。

2. 实现步骤

2.1 引入高德地图SDK

首先需要在小程序的 page.json 文件中添加高德地图SDK的引用地址:

{
  "usingComponents": {
    "amap": "path/to/amap/amap"
  }
}

然后通过 npm 安装 wx-amap-graphicswx-amap-wx 模块:

npm i wx-amap-graphics wx-amap-wx --save

在小程序页面中引入:

import Amap from './libs/amap-wx.js'
import AmapGraphics from './libs/amap-wx-graphics.js'

2.2 获取定位信息

wx.getLocation({
  type: 'gcj02',
  success(res) {
    console.log(res)
  }
})

wx.getLocation() 函数是微信小程序提供的获取用户地理位置的接口。其中 type 参数指定了返回值的坐标系,gcj02 是中国国家测绘局制定的坐标系,也是高德地图所采用的坐标系。获取到用户当前所处位置后,可以用来设置起点坐标点。

2.3 实现路线规划

wx.request({
  url: 'https://restapi.amap.com/v3/direction/driving',
  data: {
    origin: `${startLocation.lng},${startLocation.lat}`,
    destination: `${endLocation.lng},${endLocation.lat}`,
    key: '高德地图Web API Key'
  },
  success(res) {
    console.log(res)
  }
})

在路线规划过程中,需要使用高德地图提供的 “direction/driving” 接口,该接口实现了驾车路线的计算,并返回路线方案规划的结果。其中 {startLocation, endLocation} 是构造好的起点及终点地理位置对象。请求成功后,依据结果完成后续业务逻辑。

2.4 渲染地图

通过高德地图SDK将路线渲染至地图上。在微信小程序开发过程中,可以使用 <amap /> 组件:

<amap class="map" id="myMap" scale="15"
  polyline="{{polyline}}"
  markers="{{markers}}"
  circles="{{circles}}"
  controls="{{controls}}"
  bindcomplete="onMapComplete"
/>

其中,<amap /> 组件是高德地图的渲染组件,通过各类属性将路线及其他地理信息渲染至地图上实现展示效果。各类属性中的 markers 用于设置地图标记点,可以通过设置不同的图标及其他属性之实现对地理位置的标注;polyline 属性用于设置地图上的路径线段;controls 则用于控制地图视图上的缩放尺度等事件的控制。

3. 示例

下面是一个基于微信小程序,通过高德地图实现驾车路线规划的示例代码:

// index.js
import Amap from './libs/amap-wx.js'
import AmapGraphics from './libs/amap-wx-graphics.js'

Page({
  data: {
    startLocation: {},
    endLocation: {},
    polyline: [],
    circles: [],
    markers: [],
    controls: [{
      id: 1,
      iconPath: '/images/plus.png',
      position: {
        left: 10,
        top: 10,
        width: 40,
        height: 40
      },
      clickable: true
    }, {
      id: 2,
      iconPath: '/images/minus.png',
      position: {
        left: 10,
        top: 60,
        width: 40,
        height: 40
      },
      clickable: true
    }]
  },

  onLoad() {
    this.onCreateMap()
  },

  onCreateMap() {
    let s = wx.getSystemInfoSync()
    let w = s.windowWidth
    let h = s.windowHeight

    this.amap = new Amap.AMapWX({
      key: '高德地图Web API Key',
      version: '1.4.0'
    })

    let that = this
    this.amap.getRegeo({
      success: data => {
        let startLocation = {
          lng: data[0].longitude,
          lat: data[0].latitude
        }
        let endLocation = {
          lng: data[0].longitude + 0.015,
          lat: data[0].latitude + 0.01
        }
        that.setData({
          startLocation,
          endLocation
        })
        that.getRoute()
      },
      fail: info => {
        console.log(info)
      }
    })
  },

  getRoute() {
    wx.showLoading({
      title: '正在加载...',
    })

    let that = this
    wx.request({
      url: 'https://restapi.amap.com/v3/direction/driving',
      data: {
        origin: `${that.data.startLocation.lng},${that.data.startLocation.lat}`,
        destination: `${that.data.endLocation.lng},${that.data.endLocation.lat}`,
        key: '高德地图Web API Key'
      },
      success(res) {
        wx.hideLoading()
        console.log(res)

        let steps = res.data.route.paths[0].steps
        let path = []
        let markers = []
        let segments = []
        for (let i = 0; i < steps.length; i++) {
          let polyline = []
          let points = steps[i].polyline.split(';')
          let startPoint = {
            lng: parseFloat(points[0].split(',')[0]),
            lat: parseFloat(points[0].split(',')[1])
          }
          let endPoint = {
            lng: parseFloat(points[points.length - 1].split(',')[0]),
            lat: parseFloat(points[points.length - 1].split(',')[1])
          }
          path.push({
            points,
            color: "#0091ff",
            width: 6
          })
          markers.push({
            iconPath: "/images/marker.png",
            longitude: startPoint.lng,
            latitude: startPoint.lat,
            width: 50,
            height: 50
          })
          if (i === 0) {
            segments.push({
              start: that.data.startLocation,
              end: startPoint
            })
          } else {
            let lastStep = steps[i - 1]
            let lastPoints = lastStep.polyline.split(';')
            let lastEndPoint = {
              lng: parseFloat(lastPoints[lastPoints.length - 1].split(',')[0]),
              lat: parseFloat(lastPoints[lastPoints.length - 1].split(',')[1])
            }
            segments.push({
              start: lastEndPoint,
              end: startPoint
            })
          }
        }
        markers.push({
          iconPath: "/images/mark_b.png",
          longitude: that.data.endLocation.lng,
          latitude: that.data.endLocation.lat,
          width: 50,
          height: 50
        })

        that.setData({
          polyline: path,
          markers: markers,
          segments: segments
        })
      },
      fail: err => {
        wx.hideLoading()
        console.log(err)
      }
    })
  },

  onMapComplete() {
    let that = this
    this.amap.createMarkers({
      markers: that.data.markers,
      success: data => {
        console.log(data)
      }
    })
    this.amap.createPolyline({
      polylines: that.data.polyline,
      success: data => {
        console.log(data)
      }
    })

    this.amap.getCenterLocation({
      success: data => {
        console.log(data)
      }
    })

    this.setData({
      circles: [{
        longitude: that.data.startLocation.lng,
        latitude: that.data.startLocation.lat,
        fillColor: '#FF000033',
        radius: 80
      }, {
        longitude: that.data.endLocation.lng,
        latitude: that.data.endLocation.lat,
        fillColor: '#FF000033',
        radius: 80
      }]
    })
  },

  handleClickControl(e) {
    let id = e.controlId
    let scale = this.amap.getScale()
    if (id === 1) {
      scale += 1
    } else {
      scale -= 1
    }
    this.amap.setScale(scale)
  }
})

另外,这里还需注意将页面中 amap 组件的尺寸及其他属性进行添加和设置以达到最终的路线及地图展示的效果。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:微信小程序 高德地图路线规划实现过程详解 - Python技术站

(0)
上一篇 2023年5月30日
下一篇 2023年5月30日

相关文章

  • PHP计算数组中值的和与乘积的方法(array_sum与array_product函数)

    当我们需要对一个数组中的所有元素进行计算并得到计算结果时,PHP提供了array_sum函数和array_product函数来进行求和和求积的操作。 array_sum函数 array_sum函数可以用于计算数组中所有元素的和,并返回和的值。具体的用法如下: <?php $array = [1, 2, 3, 4, 5]; $sum = array_su…

    PHP 2023年5月26日
    00
  • 简单谈谈PHP vs Node.js

    简单谈谈PHP vs Node.js 前言 本文旨在探讨PHP和Node.js这两种Web开发语言的异同,并提供一些使用示例供读者参考。本文并非对PHP和Node.js的全面对比,仅供参考。 PHP和Node.js的异同 PHP和Node.js都是用于Web开发的语言,但它们的设计理念和实现方式却有很大的差异。下面我们将从几个方面来简单谈谈它们的异同。 编程…

    PHP 2023年5月26日
    00
  • 解析php获取字符串的编码格式的方法(函数)

    在PHP中,要获取一个字符串的编码格式,可以使用以下3种方法: mb_detect_encoding函数 mb_detect_encoding函数是PHP内置的多字节字符集检测函数,可以用于检测字符串的编码格式。使用该函数前,需要确保PHP的mbstring扩展已经安装并启用。 该函数的语法如下: string mb_detect_encoding ( st…

    PHP 2023年5月26日
    00
  • PHP判断是否为空的几个函数对比

    关于PHP中判断是否为空的函数有几个,下面我会仔细讲解,并且提供一些代码示例帮助理解。 1. empty函数 empty函数用于判断变量是否为空,如果变量为空则返回true,否则返回false。空变量包括空字符串、0、NULL、空数组、false。但是需要注意的是,如果变量未声明或者被赋值为的是字符串”0″,那么empty函数返回的依然是true。 下面是一…

    PHP 2023年5月26日
    00
  • thinkphp实现like模糊查询实例

    下面是“thinkphp实现like模糊查询实例”的完整攻略。 1. 创建模型 在ThinkPHP中,我们需要使用模型来完成对表的操作。在本实例中,我们需要创建一个专门用来处理like模糊查询的模型。 <?php namespace app\index\model; use think\Model; class Article extends Mode…

    PHP 2023年5月26日
    00
  • php中实现字符串翻转的方法

    要实现字符串翻转,可以使用PHP内置函数strrev(),也可以手动实现。 使用strrev()函数 strrev()函数将字符串反转,它只需一个参数,即要反转的字符串。下面是示例代码: $str = "abcdefg"; $reversed = strrev($str); echo $reversed; // 输出 "gfed…

    PHP 2023年5月26日
    00
  • php实现读取超大文件的方法

    当需要读取超大文件时,由于文件大小超过了PHP可用内存的限制,我们不能直接通过 file_get_contents() 或 fread() 这样的函数来读取文件。下面介绍几种PHP实现读取超大文件的方法。 方法一:使用fread() 调用fread()函数读取超大文件可以减少内存消耗。示例代码如下: $handle = fopen("huge_fi…

    PHP 2023年5月26日
    00
  • PHP实现基本留言板功能原理与步骤详解

    针对“PHP实现基本留言板功能原理与步骤详解”,我来详细讲解一下。 首先,基本留言板功能需要实现以下几项功能: 显示留言列表 提交留言 删除留言 以下是具体步骤: 建立数据库 在MySQL中,可以用以下代码新建一个留言板数据库及数据表: CREATE DATABASE my_guestbook; USE my_guestbook; CREATE TABLE …

    PHP 2023年5月27日
    00
合作推广
合作推广
分享本页
返回顶部