1、获取用户地理位置: 使用 wx.getLocation
API 获取用户当前的经纬度坐标。
wx.getLocation({
type: 'gcj02',
success(res) {
const latitude = res.latitude;
const longitude = res.longitude;
// 处理获取到的用户位置信息
}
});
2、选择终点位置: 选择你要显示路线的终点经纬度坐标。
3、使用地图组件: 在小程序页面中使用 map
组件,设置 markers
属性显示起点和终点。
data: {
rides: {},
markers: [], //起点和终点
distance: '', //路长
cost: '', //花费时间
polyline: [], //路线
},
// 设置起点和终点坐标
this.setData({
markers: [{
iconPath: "../../images/e.png",
id: 1,
latitude: '',
longitude: '',
width: 23,
height: 33
}, {
iconPath: "../../images/s.png",
id: 0,
latitude: '',
longitude: '',
width: 24,
height: 34
}]
})
4、显示路线: 通过 polyline
属性可以显示路线。在上述例子中,polyline
是一个包含起点和终点坐标的数组。
5、地图导航: 如果你想要提供导航功能,你可以使用 wx.openLocation
API 打开微信地图,显示起点和终点位置。
// 规划线路
setDynamicLocation() {
var that = this;
var key = "cae83d7faee406572cfab072f1c01b1d";
var myAmapFun = new amapFile.AMapWX({
key: key
});
// 起点
var startPoint = this.data.markers[1].longitude + "," + this.data.markers[1].latitude
// 目的地
var endPoint = this.data.markers[0].longitude + "," + this.data.markers[0].latitude
myAmapFun.getRidingRoute({
origin: startPoint,
destination: endPoint,
success: function (data) {
console.log(data);
var points = [];
if (data.paths && data.paths[0] && data.paths[0].rides) {
var rides = data.paths[0].rides;
that.setData({
rides: data.paths[0].rides
});
for (var i = 0; i < rides.length; i++) {
var poLen = rides[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])
})
}
}
}
that.setData({
polyline: [{
points: points,
color: "#0091ff",
width: 6
}]
});
if (data.paths[0] && data.paths[0].distance) {
that.setData({
distance: data.paths[0].distance + '米'
});
}
if (data.paths[0] && data.paths[0].duration) {
that.setData({
cost: parseInt(data.paths[0].duration / 60) + '分钟'
});
}
},
fail: function (info) {}
})
},
6、wxml代码
<!--pages/routepage/map/routemap.wxml-->
<view class="all">
<!-- 上半部 -->
<view class="mapoutbox">
<view class="map_box">
<map id="navi_map" longitude="{{markers[1].longitude}}" latitude="{{markers[1].latitude}}" scale="12" markers="{{markers}}" show-location="true" polyline="{{polyline}}"></map>
</view>
</view>
<!-- 下半部 -->
<view class="downbox">
<scroll-view scroll-y="true" style="height: 600rpx;">
<view>
本节路程全长:{{distance}}
</view>
<view>
预计花费:{{cost}}
</view>
<!-- 步行路程 -->
<view class="text_box" wx:for="{{rides}}" wx:key="id" wx:for-item="i">
{{i.instruction}}
</view>
<!-- 步行路程 -->
</scroll-view>
</view>
</view>
7、效果
