最近在忙着些小程序,今天给大家分享怎样获取当前位置,话不多说上代码,,,
css 部分
index.wxml
当前地址: <text class='m-bbt'>{{province}} {{city}}</text>
js部分
-
申请开发者密钥(key):申请密钥
申请密钥的时候下面这些都要选择,否者后期会提示你选择
JavascriptAPI 地图SDK ( Android/iOS ) WebServiceAPI 地图组件 -
下载微信小程序JavaScriptSDK,微信小程序JavaScriptSDK v1.0 下载完成后放入utils文件夹下引用即可
-
安全域名设置,在“设置” -> “开发设置”中设置request合法域名,添加https://apis.map.qq.com.
-
一切准备就绪,上代码。
index.js
/
const app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
data: {
province: '',
city: '',
latitude: '',
longitude: ''
},
onLoad: function () {
qqmapsdk = new QQMapWX({
key: 'xxxx-xxxx-xxxx-xxxx' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
});
},
onShow: function () {
let vm = this;
vm.getUserLocation();
},
getUserLocation: function () {
let vm = this;
wx.getSetting({
success: (res) => {
console.log(JSON.stringify(res))
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
let district = res.result.ad_info.district
vm.setData({
province: province, //省
city: city, //市
district: district, //区
latitude: latitude,
longitude: longitude
})
},
fail: function (res) {
console.log(res);
},
complete: function (res) {
// console.log(res);
}
});
}
})
以上代码就完成了获取本地位置的信息。如果你有其他需求还请观看文档来编写需求,好了我要忙了,拜拜。