推荐答案
// www.javascriptcn.com code example
wx.getLocation({
type: 'gcj02', // 返回可以用于wx.openLocation的经纬度
success(res) {
const latitude = res.latitude
const longitude = res.longitude
wx.openLocation({
latitude,
longitude,
scale: 18 // 缩放比例,范围5~18
})
}
})本题详细解读
1. wx.getLocation 获取当前位置
wx.getLocation 是微信小程序提供的 API,用于获取用户当前的经纬度。通过设置 type 参数为 'gcj02',可以获取到符合微信地图标准的经纬度坐标。
2. wx.openLocation 打开地图
wx.openLocation 是微信小程序提供的 API,用于打开微信内置地图,并显示指定的位置。需要传入以下参数:
latitude: 纬度,浮点数,范围为 -90~90。longitude: 经度,浮点数,范围为 -180~180。scale: 缩放比例,范围为 5~18,数值越大,地图显示的细节越多。
3. 使用场景
wx.openLocation 通常用于在微信小程序中展示某个具体的地理位置,比如商家地址、活动地点等。用户可以通过点击按钮或链接,直接打开地图查看该位置。
4. 注意事项
- 使用
wx.getLocation和wx.openLocation时,需要在app.json中配置相应的权限:{ "permission": { "scope.userLocation": { "desc": "你的位置信息将用于小程序位置接口的效果展示" } } } - 用户需要授权小程序获取地理位置信息,否则
wx.getLocation会失败。 wx.openLocation打开的地图是微信内置的地图,用户可以直接在地图上进行导航等操作。