微信小程序获取当前所在城市
本篇文章主要讲解在微信小程序中,如何利用微信自带的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
版权声明:本文为博主原创文章,转载请附上博文链接!
最新文章
- JS中的宽高(基础知识很重要)
- ASP.NET MVC URL重写与优化(1)-使用Global路由表定制URL
- matlab演奏最炫民族风的代码注释
- Oracle corrupt block(坏块) 详解
- 一段SQL代码的压缩:从974行到96行,十倍压缩
- iOS 5 故事板入门(3)
- LeetCode OJ 235. Lowest Common Ancestor of a Binary Search Tree
- Angular回到顶部按钮指令
- cf255C Almost Arithmetical Progression
- angular学习(四)-- Controller
- hadoop基础与实践--流程解惑
- myBatis各种依赖包
- 质量团队在VUCA时代如何走?
- 【Python】利用正则解析xml练习题
- SQL中Union和UnionAll的使用
- Three ways to make your WPF images pop out on MouseOver
- eclipse文本编码格式修改为UTF-8
- centos7 編譯 chmsee
- 动态规划:LIS优化
- Java-小技巧-005-double类型保留两位小数4种方法