欢迎来到258分享网,纯净的网络源码分享基地!

258资源分享网

全部作品
全部作品
网站源码
微信源码
素材特效
源码插件
视频教程
建站学院
热门搜索: 织梦  农业种植  农业  安全设置  官方
258资源分享 > 建站学院 > 微信开发 > 微信小程序获取当前所在城市

推荐下载

HTML5响应式自适应网咯设计

2020-05-12   浏览:740

高端HTML5响应式企业通用网

2020-05-06   浏览:521

html5响应式外贸网站英文版

2020-05-08   浏览:510

HTML5自适应律师工作室类网

2020-04-04   浏览:504

HTML5影视传媒文化公司类网

2020-05-12   浏览:500

微信小程序获取当前所在城市

发布时间:2020-11-18  

本篇文章主要讲解在微信小程序中,如何利用微信自带的api(wx.getLocation())结合百度地图的逆地址解析api来获取当前所在城市名。

实现起来也比较简单,步骤为:

1--利用微信小程序接口 wx.getLocation() 获取当前经纬度。使用简单,具体可以参照微信小程序api。

https://mp.weixin.qq.com/debug/wxadoc/dev/api/location.html#wxopenlocationobject

2--拿到经纬度之后,通过微信的wx.request()方法请求百度地图的解析接口,传入我们获取到的经纬度,拿到当前定位的城市。

接口为:

[javascript] view plain copy

 

 print?

url: 'https://api.map.baidu.com/geocoder/v2/?ak=您的ak&location=' + latitude + ',' + longitude + '&output=json'  

ak需要在百度地图api官网去注册,然后创建一个应用,如此便可拿到您的ak。

index.js代码如下:

[javascript] view plain copy

 

 print?

Page({  

  data: {  

    currentCity: ''  

  },  

  onLoad: function (options) {  

    this.getLocation();  

  },  

  getLocation: function () {  

    var page = this  

    wx.getLocation({  

      type: 'wgs84',   //<span class="comment" style="margin: 0px; padding: 0px; border: none;">默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标</span><span style="margin: 0px; padding: 0px; border: none;"> </span>  

      success: function (res) {  

        // success    

        var longitude = res.longitude  

        var latitude = res.latitude  

        page.loadCity(longitude, latitude)  

      }  

    })  

  },  

  loadCity: function (longitude, latitude) {  

    var page = this  

    wx.request({  

      url: 'https://api.map.baidu.com/geocoder/v2/?ak=您的ak&location=' + latitude + ',' + longitude + '&output=json',  

      data: {},  

      header: {  

        'Content-Type': 'application/json'  

      },  

      success: function (res) {  

        // success    

        console.log(res);  

        var city = res.data.result.addressComponent.city;  

        page.setData({ currentCity: city });  

      },  

      fail: function () {  

        page.setData({ currentCity: "获取定位失败" });  

      },  

        

    })  

  }  

})    

loadCity()方法中,获取到信息之后打印出来,拿到的信息是非常详细的,如下图:

微信小程序获取当前所在城市