在 app.json
中添加用户位置权限声明,确保获取定位功能可用:
"permission": { "scope.userLocation": { "desc": "你的位置信息将用于地图展示和导航" } }
在页面 WXML 中引入地图组件,并设置初始参数:
通过 wx.getLocation
获取用户当前经纬度,并初始化地图中心点:
Page({ data: { longitude: '', latitude: '', markers: [] }, onLoad() { wx.getLocation({ type: 'gcj02', // 使用国测局坐标系 success: (res) => { this.setData({ longitude: res.longitude, latitude: res.latitude }); this.loadMarkers(); // 加载标记点 } }); } });
定义 markers
数组,包含标记点的经纬度、图标等信息:
loadMarkers() { const markers = [ { id: 1, latitude: 31.2304, // 目标纬度 longitude: 121.4737, // 目标经度 iconPath: '/images/marker.png', width: 30, height: 30, callout: { // 点击标记点后的弹窗信息 content: '目标位置\n地址:上海市黄浦区', bgColor: '#fff', padding: 10, borderRadius: 5 } } ]; this.setData({ markers }); }
绑定 bindmarkertap
事件,点击标记点时触发弹窗或跳转逻辑:
onMarkerTap(e) { const markerId = e.detail.markerId; const targetMarker = this.data.markers.find(m => m.id === markerId); wx.showModal({ title: targetMarker.callout.content, confirmText: '导航至此' }); }
通过 wx.openLocation
调用微信内置地图,传入目标经纬度实现导航:
navigateToTarget() { const target = this.data.markers[0]; wx.openLocation({ latitude: target.latitude, longitude: target.longitude, name: '目标位置', address: '上海市黄浦区', scale: 18 }); }
上一篇:微信小程序如何解构赋值与普通赋值