高德-根据经纬度换算地点名称,你可能会忽略的这个问题

记录一下这个让我耗时将近1h左右才定位到的bug。

小程序里通常有一个很普遍的需求,那就是【定位授权】。而小程序里返回的数据只有经纬度以及详细地点,而需要是要获取当前定位的省/市。那么一般的处理方式,都是拿当前的经纬度去高德api换取city或者province。

而当获取直辖市的时候,city的数据是空,大家有几个发现了呢?

我就是没有发现的其中之一,而测试在提问bug的时候,也是随机选择了上海市作为切换城市的数据,我一直以为是异步没有获取到数据,无意之间,发现切换其他省市是能获取到的,只有直辖市才没有数据。

所以,以此为戒,以我不够细心为由,记录?这个问题,附上代码

function setLatLnt(res){
    uni.setStorageSync('longitude', res.longitude)
    uni.setStorageSync('latitude', res.latitude);
    store.dispatch('infoInfo/setLonLat',({
      longitude: res.longitude,
      latitude: res.latitude,
      address: res.address
    }))
  }

  //解析经纬度
  export const getSroreAddress =  (res) =>{
    const {latitude, longitude} = res
    var myAmapFun = new amapFile.AMapWX({ key: GD_KEY});

    return new Promise(async (resolve,reject)=>{
      myAmapFun.getRegeo({
        location: `${longitude},${latitude}`, //location的格式为'经度,纬度'
        success: async(e) =>{
          const addressCom = e[0].regeocodeData.addressComponent

          await setLatLnt({
            longitude:longitude,
            latitude:latitude,
            address:addressCom.city.length ? addressCom.city : addressCom.province
          })
          await resolve(e)
        },
        fail: function (err) {
          console.log(err);
        },
      });
    })
  }
复制代码

image.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享