微信小程序-获取当前城市位置
1, 获取当前地理位置,首先要拿到用户的授权wx.openSetting;
2,微信的getLocation接口,获取当前用户的地理位置(微信返回的是经纬度,速度等参数);
3,微信没有将经纬度直接转换为地理位置,借用腾讯位置服务中关于微信小程序的地理转换JS SDK 的API(返回信息中包括国家,省,市,区,经纬度等地理位置)
步骤描述清楚以后,下面就开始按步骤操作了;(本文仅仅讲述如何获取用户地理位置的授权)
图示为获取用户地理位置授权弹窗
在用户首次进入某页面(需要地理位置授权)时候,在页面进行onLoad,onShow时候,进行调用wx.getLocation要求用户进行授权;以后每次进入该页面时,通过wx.getSetting接口,返回用户授权具体信息。
wx.getSetting接口具体API地址链接为点击打开链接
上图中scope.userLocation就是地理授权的标志;
当该标志是underfind,表示用户初次进入该页面,当该标志是false,表示用户初次进入该页面拒绝了地理授权,应进行重新要求获取授权。
wx.getSetting({
success: (res) => {
console.log(JSON.stringify(res))
// res.authSetting['scope.userLocation'] == undefined 表示 初始化进入该页面
// res.authSetting['scope.userLocation'] == false 表示 非初始化进入该页面,且未授权
// res.authSetting['scope.userLocation'] == true 表示 地理位置授权
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function (res) {
if (res.cancel) {
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) {
wx.openSetting({
success: function (dataAu) {
if (dataAu.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用wx.getLocation的API
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
}
else {
//调用wx.getLocation的API
}
}
})
在拿到用户授权以后,使用微信的API获取当前位置的经纬度微信获取位置API
// 微信获得经纬度
getLocation: function () {
let that = this;
wx.getLocation({
type: 'wgs84',
success: function (res) {
// console.log(JSON.stringify(res))
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy;
that.getLocal(latitude, longitude)
},
fail: function (res) {
console.log('fail' + JSON.stringify(res))
}
})
},
这里,我们进行使用的是腾讯位置服务;专为小程序开发者提供LBS数据服务工具包,可以在小程序中调用腾讯位置服务的POI检索、关键词输入提示、地址解析、逆地址解析、行政区划和距离计算等数据。
1,得到开发者秘钥
2,下载微信小程序javaScriptSDK,
3,安全域名设置,在“设置” -> “开发设置”中设置request合法域名,添加http://api.map.qq.com
在文件中引入对应的javaScriptSDK文件
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
在文件中进行js调用,
// 获取当前地理位置
getLocal: function (latitude, longitude) {
let that = this;
let serverUrl = that.globalData.serverUrl
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
//console.log(JSON.stringify(res));
// let province = res.result.ad_info.province
let city = res.result.ad_info.city
// console.log(province + '-----' + city);
// that.setData({
// province: province,
// city: city,
// latitude: latitude,
// longitude: longitude
// })
//根据城市名称在后台数据库查询出对应的id
wx.request({
url: serverUrl + '/wx/ma/getAreaIdByAreaName?areaName=' + city,
success(res) {
//保存到缓存中
let user = that.globalData.user
user.cityId = res.data.areaId
user.cityName = res.data.areaName
that.globalData.user = user
wx.setStorageSync('user', user)
},
fail(res) {
console.log("/wx/ma/getAreaIdByAreaName", res.data)
}
})
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
// console.log(res);
}
});
},
只在小程序加载的时候调用一次,所以写在app.js里面
const util = require('utils/util.js')
var QQMapWX = require('utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
key: '开发者自己申请的key'
});
App({
onShow: function() {
},
onLaunch: function() {
wx.getSetting({
success: (res) => {
console.log(JSON.stringify(res))
// res.authSetting['scope.userLocation'] == undefined 表示 初始化进入该页面
// res.authSetting['scope.userLocation'] == false 表示 非初始化进入该页面,且未授权
// res.authSetting['scope.userLocation'] == true 表示 地理位置授权
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
_this.getLocation();
} else if (res.authSetting['scope.userLocation'] == true) {
//调用wx.getLocation的API
_this.getLocation();
}
}
})
},
// 微信获得经纬度
getLocation: function () {
let that = this;
wx.getLocation({
type: 'wgs84',
success: function (res) {
// console.log(JSON.stringify(res))
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy;
that.getLocal(latitude, longitude)
},
fail: function (res) {
console.log('fail' + JSON.stringify(res))
}
})
},
// 获取当前地理位置
getLocal: function (latitude, longitude) {
let that = this;
let serverUrl = that.globalData.serverUrl
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
//console.log(JSON.stringify(res));
// let province = res.result.ad_info.province
let city = res.result.ad_info.city
// console.log(province + '-----' + city);
// that.setData({
// province: province,
// city: city,
// latitude: latitude,
// longitude: longitude
// })
wx.request({
url: serverUrl + '/wx/ma/getAreaIdByAreaName?areaName=' + city,
success(res) {
//保存到缓存中
let user = that.globalData.user
user.cityId = res.data.areaId
user.cityName = res.data.areaName
that.globalData.user = user
wx.setStorageSync('user', user)
},
fail(res) {
console.log("/wx/ma/getAreaIdByAreaName", res.data)
}
})
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
// console.log(res);
}
});
},
如果每次打开首页,都要提示授权,在index.js书写
//index.js
//获取应用实例
const app = getApp();
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
data: {
province: '',
city: '',
latitude: '',
longitude: ''
},
onLoad: function () {
qqmapsdk = new QQMapWX({
key: 'XXXX-XXXX-XXXX-XXXX' //这里自己的key秘钥进行填充
});
},
onShow: function () {
let vm = this;
vm.getUserLocation();
},
getUserLocation: function () {
let vm = this;
wx.getSetting({
success: (res) => {
console.log(JSON.stringify(res))
// res.authSetting['scope.userLocation'] == undefined 表示 初始化进入该页面
// res.authSetting['scope.userLocation'] == false 表示 非初始化进入该页面,且未授权
// res.authSetting['scope.userLocation'] == true 表示 地理位置授权
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
wx.showModal({
title: '请求授权当前位置',
content: '需要获取您的地理位置,请确认授权',
success: function (res) {
if (res.cancel) {
wx.showToast({
title: '拒绝授权',
icon: 'none',
duration: 1000
})
} else if (res.confirm) {
wx.openSetting({
success: function (dataAu) {
if (dataAu.authSetting["scope.userLocation"] == true) {
wx.showToast({
title: '授权成功',
icon: 'success',
duration: 1000
})
//再次授权,调用wx.getLocation的API
vm.getLocation();
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 1000
})
}
}
})
}
}
})
} else if (res.authSetting['scope.userLocation'] == undefined) {
//调用wx.getLocation的API
vm.getLocation();
}
else {
//调用wx.getLocation的API
vm.getLocation();
}
}
})
},
// 微信获得经纬度
getLocation: function () {
let vm = this;
wx.getLocation({
type: 'wgs84',
success: function (res) {
console.log(JSON.stringify(res))
var latitude = res.latitude
var longitude = res.longitude
var speed = res.speed
var accuracy = res.accuracy;
vm.getLocal(latitude, longitude)
},
fail: function (res) {
console.log('fail' + JSON.stringify(res))
}
})
},
// 获取当前地理位置
getLocal: function (latitude, longitude) {
let vm = this;
qqmapsdk.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
console.log(JSON.stringify(res));
let province = res.result.ad_info.province
let city = res.result.ad_info.city
vm.setData({
province: province,
city: city,
latitude: latitude,
longitude: longitude
})
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
// console.log(res);
}
});
}
})
最后记得在app.json添加permission
{
"pages": [
"pages/index/index"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "****",
"navigationBarTextStyle": "black"
},
"tabBar": {
"position": "bottom",
"backgroundColor": "#fff",
"borderStyle": "black",
"color": "#a9a9a9",
"selectedColor": "#ffa904",
"list": [
{
"pagePath": "pages/index/index",
"text": "好物",
"selectedIconPath": "assets/image/icon_nav_haowu_selected.png",
"iconPath": "assets/image/icon_nav_haowu.png"
},
{
"pagePath": "pages/release/release",
"text": "发布",
"selectedIconPath": "assets/image/icon_nav_publish_selected.png",
"iconPath": "assets/image/icon_nav_publish.png"
},
{
"pagePath": "pages/mine/mine",
"text": "我",
"selectedIconPath": "assets/image/icon_nav_me_selected.png",
"iconPath": "assets/image/icon_nav_me.png"
}
]
},
"permission": {
"scope.userLocation": {
"desc": " "
}
}
}