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

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

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

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

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

接口为:

url: 'https://api.map.baidu.com/geocoder/v2/?ak=您的ak&location=' + latitude + ',' + longitude + '&output=json'
ak需要在百度地图api官网去注册,然后创建一个应用,如此便可拿到您的ak。

index.js代码如下:

Page({
data: {
currentCity: ''
},
onLoad: function (options) {
this.getLocation();
},
getLocation: 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)
}
})
},
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()方法中,获取到信息之后打印出来,拿到的信息是非常详细的,如下图:

我们这里需要的是当前的city,即:res.data.result.addressComponent.city。如果项目中有需要更加丰富的信息,也可使用此方法,比较简便。

index.wxml代码如下:
<!--index.wxml-->
<view class="container">
当前城市为:{{currentCity}}
</view>

效果如下:

文章参考来自:http://blog.csdn.net/tammy1151/article/details/56494776

---------------------
作者:Tiramisu_C
来源:CSDN
原文:https://blog.csdn.net/nongweiyilady/article/details/74314747
版权声明:本文为博主原创文章,转载请附上博文链接!

最新文章

  1. JS中的宽高(基础知识很重要)
  2. ASP.NET MVC URL重写与优化(1)-使用Global路由表定制URL
  3. matlab演奏最炫民族风的代码注释
  4. Oracle corrupt block(坏块) 详解
  5. 一段SQL代码的压缩:从974行到96行,十倍压缩
  6. iOS 5 故事板入门(3)
  7. LeetCode OJ 235. Lowest Common Ancestor of a Binary Search Tree
  8. Angular回到顶部按钮指令
  9. cf255C Almost Arithmetical Progression
  10. angular学习(四)-- Controller
  11. hadoop基础与实践--流程解惑
  12. myBatis各种依赖包
  13. 质量团队在VUCA时代如何走?
  14. 【Python】利用正则解析xml练习题
  15. SQL中Union和UnionAll的使用
  16. Three ways to make your WPF images pop out on MouseOver
  17. eclipse文本编码格式修改为UTF-8
  18. centos7 編譯 chmsee
  19. 动态规划:LIS优化
  20. Java-小技巧-005-double类型保留两位小数4种方法

热门文章

  1. 微信小程序video
  2. 最新 Xilinx vivado IP许可申请
  3. react 子组件调用父组件方法
  4. JavaScript 复杂判断的优雅写法
  5. 几个加固云服务器的方法(VPS版)
  6. 30.IK分词器配置文件讲解以及自定义词库
  7. 【Codeforces 1B】Spreadsheets
  8. jQuery WEI----DIV+CSS样式li自动适应高度,自动换行,横向排列
  9. N天学习一个linux命令之xz
  10. [Angular] Why should we using Protal