小程序获取当前所在城市名

到腾讯地图开放平台申请key,
在小程序中js文件:

Page({
  data: {
    city:'北京',
    url:'https://sc.xiannianmi.cn/xns/?sysAccount=BJDDMC#/',
    arr:[
      { city:'北京市', url:'https://sc.xiannianmi.cn/xns/?sysAccount=BJDDMC#/'},
      { city: '长沙市', url:'https://sc.xiannianmi.cn/xns/?sysAccount=CSDDMC#/'},
      { city:'深圳市', url:'https://sc.xiannianmi.cn/xns/?sysAccount=SZDDMC#/'},
      { city: '日照市', url:'https://sc.xiannonglp.com/xns/?sysAccount=XNSCSLZB#/'}
    ]
  },
  onLoad() {
    let _this = this
    _this.getCenterLocation();
    // console.log(_this.data.city)
  },
  onReady: function (e) {
    // 使用 wx.createMapContext 获取 map 上下文
    this.mapCtx = wx.createMapContext('myMap')
  },
  getCenterLocation: function () {
    let _this = this
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        // console.log(res.longitude)
        // console.log(res.latitude)
        //发送请求通过经纬度反查地址信息  
        var getAddressUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + res.latitude + "," + res.longitude + "&key=你申请的key";
        _this.longitude = res.longitude;
        _this.latitude = res.latitude
        wx.request({
          url: getAddressUrl,
          success: function (result) {
            _this.setData({
              city: result.data.result.address_component.city,
            })
            console.log(result.data.result.address_component.city);
            _this.data.arr.map((item,index) => {
              if (item.city === result.data.result.address_component.city){
                _this.setData({
                  url: item.url
                })
              }
            })
           
          }
        })
      }
    })
  }
})

你可能感兴趣的:(web前端,前端,小程序)