小程序获取定位完整的封装js(uniapp)

前端菜鸟,踩坑日常 / 2023-08-08 / 原文

1.小程序获取定位,首先需要在微信公众平台,申请getLocation接口(开发管理->接口设置)

2.在manifest.json打开源码视图,增加代码

    "mp-weixin": {
        "appid": "appid","permission": {
            "scope.userLocation": {
                "desc": "获取您的地理位置"
            },
        },
        "requiredPrivateInfos": ["chooseLocation","getLocation"],
    },

3.在腾讯地图api中申请一个key,用于经纬度的逆转化(需要将腾讯地图的域名配置到微信公众平台request中)

4.封装获取定位js

let getLocation = function() {
    return new Promise((reslove) => {
   //获取设置 uni.getSetting({ success(res) {
if (res.authSetting["scope.userLocation"] || res.authSetting["scope.userLocation"] === undefined) {
            //获取定位 uni.getLocation({ type:
'gcj02', success(res) { reslove(codeAroundCity(res.latitude, res.longitude)) }, fail(err) { console.log(err); } }) } else { uni.showModal({ title: '提示', content: '为方便更好的服务您,需要获取您的位置信息!', success(res) { if (res.confirm) {
     //打开设置 uni.openSetting({ success(dataAu) {
if (dataAu.authSetting['scope.userLocation'] === true) { uni.getLocation({ type: 'gcj02', success(res) { reslove(codeAroundCity(res.latitude,res.longitude)) }, fail(err) { console.log(err); } }) } } }) } } }) } } }) }) } let codeAroundCity = function(lat, lng) { let key = '腾讯地图申请的key' return new Promise((reslove, reject) => { uni.request({ url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}`, method: 'GET', data: { key, }, success(res) { let result = res.data.result.address_component //这边需要省,市,县,所以就拿这个信息,如果需要其他信息可以参照腾讯地图api reslove(result) } }) }) } export default getLocation

5.使用,引入getLocation方法

async onLoad(){
   let res = await getLocation()//res就是获取到的信息
}

不足之处还请各位大佬指点!!!

 

设置