微信小程序獲取經緯度所在城市


小程序的wx.getLocation()獲得是經緯度並不包含地名,所以要通過經緯度用相應的地圖轉換出地名(本文使用的是百度地圖)

// 獲取坐標

onLoad: function (options) {
    wx.getLocation({
      type: 'gcj02', //wgs84/gcj02
      gltitude: true,
      isHighAccuracy: true,
      success: function (res) {
        console.log(res);
        console.log('緯度' + res.latitude);
        console.log('經度' + res.longitude);
      },
    })
 
    console.log('111222333sss');
    let _this = this;
    let l=_this.data.latitude;
    console.log(l);
    
  },

// 獲取所在城市

lodeCity: function (longitude, latitude) {
      var me = this;
      wx.request({
          url: 'https://api.map.baidu.com/reverse_geocoding/v3/?ak=獲得的AK&location=' + latitude + ',' + longitude + '&output=json',
          data: {},
          header: {
            'Content-Type': 'application/json'
          },
          success: function (res) {
              if (res && res.data) {
                console.log(res.data)
                console.log(res.data.result.addressComponent.city)
                var city = res.data.result.addressComponent.city;
                console.log('res...................');
                me.setData({
                  city: city.indexOf('市') > -1 ? city.substr(0, city.indexOf('市')) :city
                });
                console.log(city);
              }else{
                me.setData({
                  city: '獲取失敗'
                });
              }
          }
      })
  },

 

 

 1.2  百度地圖的准備工作

    1.在使用百度地圖API之前,首先要獲得百度地圖的密鑰ak,ak由百度地圖方生成;

    2.打開百度地圖開放平台,導航欄處選擇 “開發文檔” > “微信小程序JavaScript API”,在“入門指南”處有詳細介紹怎么生成密鑰ak,本文不再介紹。

      參考文檔:http://lbsyun.baidu.com/index.php?title=wxjsapi/guide/key

    3.復制生成好的ak,把ak粘貼到小程序中。其實,百度地圖有提供小程序使用的地圖api的壓縮包,但是出於小程序發布時對大小的限制,我選擇了使用鏈接。

      百度地圖線上轉換鏈接地址:https://api.map.baidu.com/geocoder/v2/?ak=獲得的AK&location=' + latitude + ',' + longitude + '&output=json'

    4.使用小程序的賬號登錄微信公眾平台(https://mp.weixin.qq.com/),在“設置” 中選擇 “開發設置”,把百度地圖api的url添加到request合法域名中。

     注意:百度地圖提供的有關於小程序API的下載包,不想使用鏈接地址的可以使用下載包,出於小程序發布時對大小的限制,本文使用的是鏈接地址未使用下載包。

 

這個開發設置我是在“開發”--“開發管理”找到的

5.此時准備工作完成,便可以直接在小程序中根據經緯度轉換出相應的地名了

 

 

 

最后:遇到API報"APP 服務被禁用":

將請求地址 https://api.map.baidu.com/geocoder/v2/

換成

https://api.map.baidu.com/reverse_geocoding/v3/

 

 

 

參考鏈接:https://www.cnblogs.com/liuyuanfang/p/9748074.html

解決百度地圖API報"APP 服務被禁用"的參考鏈接:https://blog.csdn.net/weixin_42729938/article/details/116857796


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM