小程序之获取当前城市名

1、根据腾讯api定位(http://lbs.qq.com/uri_v1/guide-mobile.html

url:https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${app.globalData.tencentMapKey}
// latitude longitude 可以根据小程序的 wx.getLocation 获取
// app.globalData.tencentMapKey  自己在腾讯地图api的key

2、依据小程序的 wx.getLocation方法

/*
1、 app.globalData.defaultCity    在小程序app.js中先注册好的
2、app.globalData.defaultCounty
3、county
4、location
   globalData:{
        defaultCity:"",
        defaultCounty:""
    }

  county  location先在data里面注册
*/
  getLocation:function(){
    var that = this;
    wx.getLocation({
      success: function(res) {
        let latitude = res.latitude;
        let longitude = res.longitude;
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${app.globalData.tencentMapKey}`,
          success:res=>{
            app.globalData.defaultCity = app.globalData.defaultCity ? app.globalData.defaultCity : res.data.result.ad_info.city;
            app.globalData.defaultCounty = app.globalData.defaultCounty ? app.globalData.defaultCounty : res.data.result.ad_info.district;
            that.setData({
              location: app.globalData.defaultCity,  //省份
              county: app.globalData.defaultCounty //城市
            });
           
          }
        })
      },
    })
  },

3、在小程序onLoad中调用 方法 getLocation()

  onLoad:function(){
    this.getLocation();
  }

4、显示

 {{location}}{{county}}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容