likes
comments
collection
share

uniapp中小程序、H5、App使用高德地图逆解析获取用户位置信息

作者站长头像
站长
· 阅读数 212

需求

使用uniapp开发小程序+H5+App,需要获取用户位置信息,可以先获取用户经纬度信息,然后调用第三方地图Api,逆解析获取到用户实际位置信息;

最后踩坑下来发现,高德地图的逆解析比较方便,可以直接使用uniapp.request({})调用高德Api,腾讯地图在H5上会有跨域的问题,需要用jsonp解决,步骤会多一些。

获取经纬度

首先使用uni.getLocation()先获取到当前位置信息的经纬度

*注意:在H5中,使用谷歌浏览器在本地环境调用uni.getLocation()可能没有响应,猜测是在国内获取位置信息无法访问到谷歌服务器,火狐浏览器在本地可以成功调试,获取到经纬度信息。

function getLocation () {
  uni.getLocation({
    type: 'wgs84',
    isHighAccuracy: true, // 开启高精度定位
    success: (res) => {
      console.log('当前位置的经度:' + res.longitude);
      console.log('当前位置的纬度:' + res.latitude);
    }
  })
}

H5、小程序根据经纬度逆解析为实际地理位置信息

  1. 进入高德开放平台,完成注册、登录
  2. 进入控制台,选择【应用管理】【我的应用】【创建新应用】

uniapp中小程序、H5、App使用高德地图逆解析获取用户位置信息

  1. 然后在列表中复制key,粘贴到下方 uniapp中小程序、H5、App使用高德地图逆解析获取用户位置信息
  2. 配置完成后,使用uni.request调用高德逆解析Api解析经纬度
uni.request({
  method: 'GET',
  url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
  data: {
    key: '刚复制的key',
    location: `${longitude},${latitude}`,
    output: 'JSON'
  },
  success: (res) => {
    console.log(res) // 数据结构见下方
  },
  fail: res => {
    reject(new Error('获取地理位置信息失败'))
  }
})
  1. 高德返回的数据格式
{
  "data": {
    "status": "1",
    "regeocode": {
      "addressComponent": {
        "city": "xx市",
        "province": "xx省",
        "adcode": "510107",
        "district": "xx区",
        "towncode": "510107021000",
        "streetNumber": {
          "number": "399号",
          "location": "104.061625,30.553908",
          "direction": "西南",
          "distance": "81.1765",
          "street": "xx路"
        },
        "country": "中国",
        "township": "xx街道",
        "businessAreas": [
          []
        ],
        "building": {
          "name": [],
          "type": []
        },
        "neighborhood": {
          "name": [],
          "type": []
        },
        "citycode": "028"
      },
      "formatted_address": "xx省xx市xx区xx街道xx"
    },
    "info": "OK",
    "infocode": "10000"
  },
  "statusCode": 200,
  "header": {
    "content-length": "593",
    "content-type": "application/json;charset=utf-8"
  },
  "errMsg": "request:ok"
}

App获取位置信息

在App中可以直接调用uni.getLocation()获取到具体位置信息:

uni.getLocation({
  type: 'gcj02', // 必须设置为gcj02
  geocode: true , // 是否解析地址信息,仅App支持
  isHighAccuracy: true, // 开启高精度
  success: (res) => {
    console.log(res) // 数据结构见下方
  },
  fail: (err) => {
    console.log(err)
  }
})

返回的数据格式

{
  "type": "gcj02",
  "altitude": 0,
  "latitude": 30.624786,
  "longitude": 103.956749,
  "speed": 0,
  "accuracy": 50,
  "address": {
    "country": "中国",
    "province": "xx省",
    "city": "xx市",
    "district": "xx区",
    "street": "xx路",
    "streetNum": "xx号",
    "poiName": "xxx小区",
    "cityCode": "028"
  },
  "errMsg": "getLocation:ok"
}

使用Promise封装三端获取位置通用方法

export function getLocation() {
  return new Promise((resolve, reject) => {
    // #ifdef APP
    uni.getLocation({
      type: 'gcj02', // 必须设置为gcj02
      geocode: true, // 是否解析地址信息,仅App支持
      isHighAccuracy: true, // 开启高精度
      success: (res) => {
        resolve({
          ...res.address,
          longitude: res.longitude,
          latitude: res.latitude
        })
      },
      fail: (err) => {
        console.log(err)
        reject(new Error('获取地理位置信息失败'))
      }
    })
    // #endif
    
    // #ifndef APP
    uni.getLocation({
      type: 'wgs84',
      isHighAccuracy: true, // 开启高精度定位
      success: ({ longitude, latitude }) => {
        uni.request({
          method: 'GET',
          url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
          data: {
            key: '刚复制的key',
            location: `${longitude},${latitude}`,
            output: 'JSON'
          },
          success: ({ data }) => {
            const { addressComponent, formatted_address } = data.regeocode
            const [longitude, latitude] = addressComponent.streetNumber.location.split(',')
            resolve({
              longitude,
              latitude,
              province: addressComponent.province,
              city: addressComponent.city,
              district: addressComponent.district,
              street: addressComponent.township,
              address: formatted_address
            })
          },
          fail: (error) => {
            console.log(error)
            reject(new Error('获取地理位置信息失败'))
          }
        })
      }
    })
    // #endif
  })
}
转载自:https://juejin.cn/post/7206195315924287548
评论
请登录