1.配置地理位置用途说明
在app.json中的大括号内输入
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于小程序位置接口的效果展示" // 小程序获取权限时展示的接口用途说明
}
}
2.在页面上添加map组件
1.在index.wxml中添加map组件
<map id="map" longitude="{{longitude}}" latitude="{{latitude}}" scale="14" markers="{{markers}}" style="position: fixed;width: 100%;height: 100%;"></map>
map组件的详细介绍见网址微信官方文档map组件
2.在index.js中编写获取用户位置信息的函数,将位置信息传入map组件的中心经纬度属性中。
(1)在data中添加需要通过函数获得的数据
data: {
longitude:"",
latitude:"",
markers:[]
},
(2)获取用户位置信息函数getMyLocation,写在data括号后
getMyLocation:function(){
var that=this;
wx.getLocation({
type: 'wgs84',
success (res) {
console.log(res);
console.log("1",that.data.latitude);
that.setData({
latitude:res.latitude,
longitude:res.longitude,
markers: [{
iconPath: "/images/MyLoc.png",
id: 0,
latitude: res.latitude,
longitude: res.longitude
}],
});
console.log("2",that.data.latitude);
}
})
}
(3)使用getMyLocation函数中的wx.getLocationAPI需要先获取用户位置信息授权,所以在监听页面加载函数onLoad中获取用户授权。
onLoad: function (options) {
var that=this;
//获取用户当前的授权状态
wx.getSetting({
success(res) {
//若用户没有授权地理位置
if (!res.authSetting['scope.userLocation']) {
//在调用需授权 API 之前,提前向用户发起授权请求
wx.authorize({
scope: 'scope.userLocation',
//用户同意授权
success () {
// 用户已经同意小程序使用地理位置,后续调用 wx.getLocation 接口不会弹窗询问
that.getMyLocation();
},
用户不同意授权
fail(){
wx.showModal({
title: '提示',
content: '此功能需获取位置信息,请授权',
success: function (res) {
if (res.confirm == false) {
return false;
}
wx.openSetting({
success(res) {
//如果再次拒绝则返回页面并提示
if (!res.authSetting['scope.userLocation']) {
wx.showToast({
title: '此功能需获取位置信息,请重新设置',
duration: 3000,
icon: 'none'
})
} else {
//允许授权,调用地图
that.onLoad()
}
}
})
}
})
}
})
}
else{
that.getMyLocation();
}
}
})
},
3.编译运行
注意:先清除缓存,否则默认开发者工具已经授权。
运行结果:
(1)选择允许,则显示用户地理位置(标记点),若用开发者工具运行,显示的位置为用户电脑IP地址所在的城市中心,若用真机调试,显示的位置为用户手机地理位置。
(2)选择不允许,则提示用户授权位置信息,用户重新授权后才显示正确地理位置。