微信小程序-獲取當前位置和城市名


微信小程序-獲取當前城市位置

   1, 獲取當前地理位置,首先要拿到用戶的授權wx.openSetting;

    2,微信的getLocation接口,獲取當前用戶的地理位置(微信返回的是經緯度,速度等參數);

    3,微信沒有將經緯度直接轉換為地理位置,借用騰訊位置服務中關於微信小程序的地理轉換JS SDK 的API(返回信息中包括國家,省,市,區,經緯度等地理位置)
步驟描述清楚以后,下面就開始按步驟操作了;(本文僅僅講述如何獲取用戶地理位置的授權)

圖示為獲取用戶地理位置授權彈窗

 

 

在用戶首次進入某頁面(需要地理位置授權)時候,在頁面進行onLoad,onShow時候,進行調用wx.getLocation要求用戶進行授權;以后每次進入該頁面時,通過wx.getSetting接口,返回用戶授權具體信息。

wx.getSetting接口具體API地址鏈接為點擊打開鏈接

 

 

 上圖中scope.userLocation就是地理授權的標志;

當該標志是underfind,表示用戶初次進入該頁面,當該標志是false,表示用戶初次進入該頁面拒絕了地理授權,應進行重新要求獲取授權。

wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化進入該頁面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化進入該頁面,且未授權
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授權
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '請求授權當前位置',
            content: '需要獲取您的地理位置,請確認授權',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒絕授權',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授權成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授權,調用wx.getLocation的API
                      
                    } else {
                      wx.showToast({
                        title: '授權失敗',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //調用wx.getLocation的API
        }
        else {
          //調用wx.getLocation的API
        }
      }
    })

在拿到用戶授權以后,使用微信的API獲取當前位置的經緯度微信獲取位置API

 

 

這里,我們進行使用的是騰訊位置服務;專為小程序開發者提供LBS數據服務工具包,可以在小程序中調用騰訊位置服務的POI檢索、關鍵詞輸入提示、地址解析、逆地址解析、行政區划和距離計算等數據。
    1,得到開發者秘鑰
    2,下載微信小程序javaScriptSDK,

    3,安全域名設置,在“設置” -> “開發設置”中設置request合法域名,添加http://api.map.qq.com

在文件中引入對應的javaScriptSDK文件

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

在文件中進行js調用

 

 最后的結果就是可以獲得自己所在城市的具體位置了

 

index.js部分的代碼

 

//index.js
//獲取應用實例
const app = getApp();
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  data: {
    province: '',
    city: '',
    latitude: '',
    longitude: ''
  },
  onLoad: function () {
    qqmapsdk = new QQMapWX({
      key: 'XXXX-XXXX-XXXX-XXXX' //這里自己的key秘鑰進行填充
    });
  },
  onShow: function () {
    let vm = this;
    vm.getUserLocation();
  },
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化進入該頁面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化進入該頁面,且未授權
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授權
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '請求授權當前位置',
            content: '需要獲取您的地理位置,請確認授權',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒絕授權',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授權成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授權,調用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授權失敗',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //調用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //調用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信獲得經緯度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 獲取當前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude
        })
 
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  }
})

頁面展示部分的代碼

<!--index.wxml-->
<view class="retailStore">
   <view class="cnaps  borderBottom">
    <text>所在城市</text>
    <input class='m-bbt' placeholder-class='plhStyle' type='number' maxlength='50' placeholder='' bindinput="bindKeyInput" value='{{province}} {{city}}' disabled></input>
  </view>
</view>

版權聲明:本文為CSDN博主「Anita梅梅」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_42262436/article/details/80458430


免責聲明!

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



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