推荐答案
在微信小程序中,可以使用 map 组件和 wx.getLocation API 来绘制路线。以下是一个简单的实现步骤:
获取用户当前位置: 使用
wx.getLocation获取用户的当前位置坐标。设置地图中心点: 将获取到的用户位置设置为地图的中心点。
绘制路线: 使用
map组件的polyline属性来绘制路线。polyline是一个数组,包含多个坐标点,表示路线的路径。显示地图: 在页面的
wxml文件中使用map组件,并绑定polyline数据。
// www.javascriptcn.com code example
Page({
data: {
latitude: 0,
longitude: 0,
polyline: []
},
onLoad() {
this.getUserLocation();
},
getUserLocation() {
wx.getLocation({
type: 'wgs84',
success: (res) => {
this.setData({
latitude: res.latitude,
longitude: res.longitude
});
this.drawRoute();
}
});
},
drawRoute() {
const polyline = [{
points: [
{ latitude: this.data.latitude, longitude: this.data.longitude },
{ latitude: 31.2304, longitude: 121.4737 } // 目标位置坐标
],
color: '#FF0000',
width: 2,
dottedLine: false
}];
this.setData({ polyline });
}
});<map
id="map"
latitude="{{latitude}}"
longitude="{{longitude}}"
markers="{{markers}}"
polyline="{{polyline}}"
style="width: 100%; height: 300px;">
</map>本题详细解读
1. 获取用户当前位置
wx.getLocation 是微信小程序提供的获取用户当前位置的 API。通过设置 type 为 wgs84,可以获取到经纬度坐标。
2. 设置地图中心点
获取到用户的位置后,将 latitude 和 longitude 设置为地图的中心点,这样地图会以用户当前位置为中心显示。
3. 绘制路线
polyline 是 map 组件的一个属性,用于在地图上绘制折线。points 数组中的每个对象表示一个坐标点,color 和 width 分别设置折线的颜色和宽度。
4. 显示地图
在 wxml 文件中使用 map 组件,并绑定 latitude、longitude 和 polyline 数据,地图会根据这些数据渲染出用户当前位置和绘制的路线。
通过以上步骤,可以在微信小程序的地图上绘制出从用户当前位置到目标位置的路线。