首页 > 课堂 > 小程序 > 正文

微信小程序定位当前城市的方法

2020-03-21 16:13:07
字体:
来源:转载
供稿:网友

微信小程序定位获取当前所在城市,供大家参考,具体内容如下

1、利用微信小程序接口 wx.getLocation() 获取当前经纬度,接口

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

微信小程序,定位,当前城市

Page({ data: { city: '' }, onLoad: function (options) {  this.loadInfo();  }, loadInfo: function () { var page = this wx.getLocation({  type: 'wgs84', // 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于 wx.openLocation 的坐标   success: function (res) {  // success   var longitude = res.longitude  var latitude = res.latitude  page.loadCity(longitude, latitude)  },  fail: function () {  // fail   },  complete: function () {  // complete   } }) },  loadCity: function (longitude, latitude) { var page = this wx.request({  url: 'http://api.map.baidu.com/geocoder/v2/?ak=写自己的ak&location=' + latitude + ',' + longitude + '&output=json&pois=1',  //这里的ak 是去百度地图api获取的需要自己登陆获取一下 地址:https://lbsyun.baidu.com/index.php?title=wxjsapi  data: {},  header: {  'Content-Type': 'application/json'  },  success: function (res) {  // success   console.log(res);  var city = res.data.result.addressComponent.city;   console.log("城市为" + city)  page.setData({ city: city });  },  fail: function () {  // fail   },  complete: function () {  // complete   } }) }});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表