微信小程序获取当前城市定位

获取当前城市 一般需要二步骤

1 getLocation 获取精度,维度

2 然后请求,百度,高度,腾讯题图转换即可

这里以百度地图为例

代码如下

wx.getLocation({
    success: function(res) {
      console.log(res)
      var longitude = res.longitude
      var latitude = res.latitude
      that.curCity(longitude, latitude)
    },
  })
  },
  curCity: function (longitude, latitude){
   wx.request({
     url: 'https://api.map.baidu.com/geocoder/v2/?ak=自己到百度地图创建获取的ak&location=' + latitude + ',' + longitude + '&output=json&pois=1',
     data:{},
     header: {
       'Content-Type': 'application/json'
     },
     success:function(res){
       console.log(res);
       var city = res.data.result.addressComponent.city
       console.log("定位的城市"+city)
       
         
     }
   })
  },

这个就能得到当前所在位置的城市了

注意:ak要到百度地图开放平台申请即可,如果填写不能会报错, getLocation使用的使用记得添加权限,如果不添加不提示添加的

你可能感兴趣的:(微信小程序,微信小程序)