微信小程序使用map组件实现路线规划功能示例


Posted in Javascript onJanuary 22, 2019

本文实例讲述了微信小程序使用map组件实现路线规划功能。分享给大家供大家参考,具体如下:

效果图

微信小程序使用map组件实现路线规划功能示例

实现原理

1. 通过map组件标记起始点和绘制路线图;
2. 通过高德地图API获取不同类型的路线坐标点,以及耗费时间和路程。

WXML

<view class="flex-style">
 <view class="flex-item {{status == 'car' ? 'active' : ''}}" data-status="car" bindtouchstart="goTo">驾车</view>
 <view class="flex-item {{status == 'walk' ? 'active' : ''}}" data-status="walk" bindtouchstart="goTo">步行</view>
 <view class="flex-item {{status == 'bus' ? 'active' : ''}}" data-status="bus" bindtouchstart="goTo">公交</view>
 <view class="flex-item {{status == 'ride' ? 'active' : ''}}" data-status="ride" bindtouchstart="goTo">骑行</view>
</view>
<view class="map-inputtips-input">
 <input bindinput="bindInput" placeholder="输入终点" focus="true" />
</view>
<view class="map-search-list {{isShow ? '' : 'map-hide'}}">
 <view bindtouchstart="bindSearch" wx:key="searchId" data-keywords="{{item.name}}" data-location="{{item.location}}" class="map-box" wx:for="{{tips}}">
  {{item.name}}
 </view>
</view>
<view class="map_box {{detailStatus ? 'active' : ''}}">
 <map id="navi_map" longitude="{{longitude}}" latitude="{{latitude}}" scale="14" include-points='{{points}}' markers="{{markers}}" polyline="{{polyline}}"></map>
</view>
<view class="text_box {{detailStatus ? '' : 'map-hide'}}">
 <view class="text">路程:{{distance}}米</view>
 <view class="text">耗时:{{cost}}分钟</view>
 <view class="detail_button" bindtouchstart="goDetail">详情</view>
</view>

WXSS

.flex-style{
 display: -webkit-box;
 display: -webkit-flex;
 display: flex;
}
.flex-item{
 height: 35px;
 line-height: 35px;
 text-align: center;
 -webkit-box-flex: 1;
 -webkit-flex: 1;
 flex: 1
}
.flex-item.active{
 color:#0091ff;
}
.map_box{
 position:absolute;
 top: calc(35px + 80rpx);
 bottom: 0px;
 left: 0px;
 right: 0px;
}
.map_box.active{bottom: 90px;}
#navi_map{
 width: 100%;
 height: 100%;
}
.text_box{
 position:absolute;
 height: 90px;
 bottom: 0px;
 left: 0px;
 right: 0px;
}
.text_box .text{
 margin: 15px;
 color: lightseagreen;
}
.detail_button{
 position:absolute;
 bottom: 30px;
 right: 10px;
 padding: 3px 5px;
 color: #fff;
 background: #0091ff;
 width:50px;
 text-align:center;
 border-radius:5px;
}
.map-inputtips-input{
 height: 80rpx;
 line-height: 80rpx;
 width: 100%;
 box-sizing: border-box;
 font-size: 30rpx;
 padding: 0 10px;
 background-color: #fff;
 position: fixed;
 top: 35px;
 left: 0;
 z-index: 1000;
 border-bottom:1px solid #c3c3c3;
}
.map-inputtips-input input{
 border: 1px solid #ddd;
 border-radius: 5px;
 height: 60rpx;
 line-height: 60rpx;
 width: 100%;
 box-sizing: border-box;
 padding: 0 5px;
 margin-top: 10rpx;
}
.map-box{
 margin: 0 10px;
 border-bottom:1px solid #c3c3c3;
 height: 80rpx;
 line-height: 80rpx;
}
.map-box:last-child{border: none;}
.map-search-list{
 position: fixed;
 top: calc(80rpx + 35px);
 left: 0;
 width: 100%;
 z-index: 1000;
 background-color: #fff;
}

JS

const app = getApp();
const amap = app.data.amap;
const key = app.data.key;
Page({
 data: {
  longitude: '',
  latitude: '',
  isShow: false,
  detailStatus: false,
  status: '',
  markers: [],
  points: [],
  distance: '',
  cost: '',
  city: '',
  tips: {},
  polyline: []
 },
 onLoad() {
  var _this = this;
  wx.getLocation({
   success: function (res) {
    if (res && res.longitude) {
     _this.setData({
      longitude: res.longitude,
      latitude: res.latitude,
      points: [{
       longitude: res.longitude,
       latitude: res.latitude
      }],
      markers: [{
       id: 0,
       longitude: res.longitude,
       latitude: res.latitude,
       iconPath: '../../src/images/navi_s.png',
       width: 32,
       height: 32
      }]
     })
    }
   }
  })
 },
 bindInput: function (e) {
  var _this = this;
  var keywords = e.detail.value;
  var myAmap = new amap.AMapWX({ key: key });
  myAmap.getInputtips({
   keywords: keywords,
   location: '',
   success: function (res) {
    if (res && res.tips) {
     var address = res.tips[0].district;
     _this.setData({
      isShow: true,
      city: address.substring(address.indexOf('省') + 1, address.indexOf('市')),
      tips: res.tips
     });
    }
   }
  })
 },
 bindSearch: function (e) {
  var keywords = e.target.dataset.keywords;
  var location = e.target.dataset.location;
  location = location.split(',');
  if (this.data.markers.length > 1 && this.data.points.length > 1){
   this.data.markers.pop();
   this.data.points.pop();
   this.setData({ polyline:[]});
  }
  var markers = this.data.markers;
  var points = this.data.points;
  markers.push({
   id: 0,
   longitude: location[0],
   latitude: location[1],
   iconPath: '../../src/images/navi_e.png',
   width: 32,
   height: 32
  });
  points.push({
   longitude: location[0],
   latitude: location[1]
  })
  this.setData({
   isShow: false,
   markers: markers,
   points: points
  })
 },
 goTo(e) {
  if (this.data.points.length < 2) {
   wx.showToast({ title: '请输入终点' })
   return;
  }
  var status = e.target.dataset.status;
  var myAmap = new amap.AMapWX({ key: key });
  switch (status) {
   case 'car':
    myAmap.getDrivingRoute(this.getDataObj('#4B0082'));
    break;
   case 'walk':
    myAmap.getWalkingRoute(this.getDataObj());
    break;
   case 'bus':
    myAmap.getTransitRoute(this.getBusData('#008B8B'));
    break;
   case 'ride':
    myAmap.getRidingRoute(this.getDataObj('#00FFFF'));
    break;
   default:
    return;
  }
  this.setData({
   detailStatus: true,
   status: status
  })
 },
 getDataObj(color) {
  var _this = this;
  var color = color || "#0091ff";
  return {
   origin: _this.data.points[0].longitude + ',' + _this.data.points[0].latitude,
   destination: _this.data.points[1].longitude + ',' + _this.data.points[1].latitude,
   success(data) {
    var points = [];
    if (!data.paths || !data.paths[0] || !data.paths[0].steps) {
     wx.showToast({ title: '失败!' });
     return;
    }
    if (data.paths && data.paths[0] && data.paths[0].steps) {
     var steps = data.paths[0].steps;
     for (var i = 0; i < steps.length; i++) {
      var poLen = steps[i].polyline.split(';');
      for (var j = 0; j < poLen.length; j++) {
       points.push({
        longitude: parseFloat(poLen[j].split(',')[0]),
        latitude: parseFloat(poLen[j].split(',')[1])
       })
      }
     }
    }
    _this.setData({
     distance: data.paths[0].distance,
     cost: parseInt(data.paths[0].duration / 60),
     polyline: [{
      points: points,
      color: color,
      width: 6
     }]
    });
   },
   fail(info) {
    wx.showToast({ title: '失败!' })
   }
  }
 },
 getBusData(color) {
  var _this = this;
  var color = color || "#0091ff";
  return {
   origin: _this.data.points[0].longitude + ',' + _this.data.points[0].latitude,
   destination: _this.data.points[1].longitude + ',' + _this.data.points[1].latitude,
   city: _this.data.city,
   success(data) {
    var points = [], cost = 0;
    if (data && data.transits) {
     var transits = data.transits;
     for (var i = 0; i < transits.length; i++) {
      cost += parseInt(transits[i].duration);
      var segments = transits[i].segments;
      for (var j = 0; j < segments.length; j++) {
       if (segments[j].bus.buslines[0] && segments[j].bus.buslines[0].polyline) {
        var steps = segments[j].bus.buslines[0].polyline.split(';');
        for (var k = 0; k < steps.length; k++) {
         var point = steps[k].split(',');
         points.push({
          longitude: point[0],
          latitude: point[1]
         })
         if (parseInt(point[0] * 100000) === parseInt(_this.data.points[1].longitude * 100000) && parseInt(point[1] * 100000) === parseInt(_this.data.points[1].latitude * 100000)){
          _this.setData({
           distance: data.distance,
           cost: parseInt(cost / 60),
           polyline: [{
            points: points,
            color: color,
            width: 6
           }]
          });
          return ;
         }
        }
       }
      }
     }
    }
   },
   fail(info) {
    wx.showToast({ title: '失败!' })
   }
  }
 }
})

实现步骤

1. 利用 input 输入终点地址关键字;
2. 通过关键字利用高德地图API(getInputtips)获取地址坐标列表;
3. 列表添加选中事件,获取具体的 location ,进行地图标记;
4. 选择路线类型(驾车,骑行等),通过高德地图对应的API获取规划坐标;
5. 绘制路线。
6. 注意:在返回的路线坐标数据格式,公交和其他三种方式的数据格式不同,需要单独进行处理(单独处理公交数据的方法: getBusData)。

希望本文所述对大家微信小程序开发有所帮助。

Javascript 相关文章推荐
用javascript实现在小方框中浏览大图的代码
Aug 14 Javascript
基于jQuery的倒计时实现代码
May 30 Javascript
IE关闭时判断及AJAX注销案例学习
Feb 18 Javascript
jquery实现页面图片等比例放大缩小功能
Feb 12 Javascript
javascript中递归函数用法注意点
Jul 30 Javascript
javascript用正则表达式过滤空格的实现代码
Jun 14 Javascript
jquery表单提交带错误信息提示效果
Mar 09 Javascript
layui表格checkbox选择全选样式及功能的实例
Mar 07 Javascript
react-native 圆弧拖动进度条实现的示例代码
Apr 12 Javascript
微信小程序上线发布流程图文详解
May 06 Javascript
泛谈JS逻辑判断选择器 || &amp;&amp;
May 24 Javascript
Vue Extends 扩展选项用法完整实例
Sep 17 Javascript
JavaScript JMap类定义与使用方法示例
Jan 22 #Javascript
vue2.0 如何在hash模式下实现微信分享
Jan 22 #Javascript
JavaScript继承与聚合实例详解
Jan 22 #Javascript
JavaScript格式化json和xml的方法示例
Jan 22 #Javascript
基于vue的验证码组件的示例代码
Jan 22 #Javascript
JavaScript中的&quot;=、==、===&quot;区别讲解
Jan 22 #Javascript
深入分析element ScrollBar滚动组件源码
Jan 22 #Javascript
You might like
php查询ip所在地的方法
2014/12/05 PHP
在PHP站点的页面上添加Facebook评论插件的实例教程
2016/01/08 PHP
编写PHP程序检查字符串中的中文字符个数的实例分享
2016/03/17 PHP
php生成mysql的数据字典
2016/07/07 PHP
PHP实践教程之过滤、验证、转义与密码详解
2017/07/24 PHP
Laravel使用scout集成elasticsearch做全文搜索的实现方法
2018/11/30 PHP
来自国外的14个图片放大编辑的jQuery插件整理
2010/10/20 Javascript
javascript 日期时间 转换的方法
2013/02/21 Javascript
轻松创建nodejs服务器(6):作出响应
2014/12/18 NodeJs
jquery地址栏链接与a标签链接匹配之特效代码总结
2015/08/24 Javascript
Javascript生成全局唯一标识符(GUID,UUID)的方法
2016/02/27 Javascript
获取当前月(季度/年)的最后一天(set相关操作及应用)
2016/12/27 Javascript
EasyUI学习之DataGird分页显示数据
2016/12/29 Javascript
Vue.js基础学习之class与样式绑定
2017/03/20 Javascript
bootstrap时间插件daterangepicker使用详解
2017/10/19 Javascript
Bootstrap实现的表格合并单元格示例
2018/02/06 Javascript
简单明了区分escape、encodeURI和encodeURIComponent
2018/05/26 Javascript
微信小程序template模板与component组件的区别和使用详解
2019/05/22 Javascript
微信小程序下拉框搜索功能的实现方法
2019/07/31 Javascript
微信小程序的引导页实现代码
2020/06/24 Javascript
[53:10]完美世界DOTA2联赛决赛日 FTD vs GXR 第二场 11.08
2020/11/11 DOTA
新手该如何学python怎么学好python?
2008/10/07 Python
Django框架会话技术实例分析【Cookie与Session】
2019/05/24 Python
PYQT5实现控制台显示功能的方法
2019/06/25 Python
Python迭代器Iterable判断方法解析
2020/03/16 Python
Django查询优化及ajax编码格式原理解析
2020/03/25 Python
Keras Convolution1D与Convolution2D区别说明
2020/05/22 Python
Omio西班牙:全欧洲低价大巴、火车和航班搜索和比价
2017/02/11 全球购物
英国领先的豪华时尚家居网上商店:Amara
2019/08/12 全球购物
汽车检测与维修专业求职信
2013/10/30 职场文书
高中生家长会演讲稿
2014/01/14 职场文书
教师现实表现材料
2014/02/14 职场文书
购房公证委托书(2014版)
2014/09/12 职场文书
毕业典礼致辞
2015/07/29 职场文书
Python机器学习算法之决策树算法的实现与优缺点
2021/05/13 Python
如何在pycharm中快捷安装pip命令(如pygame)
2021/05/31 Python