博主信息
博文 5
粉丝 0
评论 0
访问量 10183
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
微信小程序获取当前所在城市 百度地图和腾讯地图
付一一的博客
原创
1688人浏览过

本篇文章主要讲解在微信小程序中,如何利用微信自带的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。

url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=你的key'


'  

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



index.js代码如下:

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()方法中,获取到信息之后打印出来,拿到的信息是非常详细的,如下图:


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


index.wxml代码如下:

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


效果如下:



本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学