欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-10 11:32:34
本文实例讲述了微信小程序使用map组件实现路线规划功能。分享给大家供大家参考,具体如下: 效果图 实现原理 1. 通过map组件标记起始点和绘制路线图; 2....

本文实例讲述了微信小程序使用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)。

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