小程序 获取当前用户城市信息(省市区)
生活随笔
收集整理的這篇文章主要介紹了
小程序 获取当前用户城市信息(省市区)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
步驟
具體步驟知識參考:https://lbs.qq.com/guides/startup.html
代碼
(1)獲取地理經緯度wx.getLocation
(2)下載微信小程序JavaScriptSDK
(3)安全域名設置,在“設置” -> “開發設置”中設置request合法域名,添加https://apis.map.qq.com
(4)小程序代碼完整示例 注意:微信小程序使用的時候,WebServiceAPI 域名白名單不能配置,否則會報錯 <text>經緯度:{{latitude}},{{longitude}}</text> <view><text>位置:</text><text>{{province}} </text><text>{{city}} </text><text>{{district}} </text> </view> <button bindtap="getLocation">獲取當前城市位置</button>var QQMapWX = require('../../libs/qqmap-wx-jssdk.js'); var qqmapsdk; Page({data: {province: '',city: '',district: '',latitude: '',longitude: '',},onLoad: function (options) {qqmapsdk = new QQMapWX({key: 'YRXBZ-42R3W-6XVRG-R3V7B-CAOE7-TQB43'});},getLocation () {let _this = thiswx.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_this.getToLocation()} else {wx.showToast({title: '授權失敗',icon: 'none',duration: 1000})}}})}}})} else if (res.authSetting['scope.userLocation'] == undefined) {//調用wx.getLocation的API_this.getToLocation()}else {//調用wx.getLocation的API_this.getToLocation()}}})},// 微信獲得經緯度getToLocation: function () {let _this = this;wx.getLocation({type: 'wgs84',success: function (res) {console.log(JSON.stringify(res))var latitude = res.latitudevar longitude = res.longitudevar speed = res.speedvar accuracy = res.accuracy;_this.setData({latitude: res.latitude,longitude: res.longitude})_this.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));console.log(res.result);let province = res.result.ad_info.provincelet city = res.result.ad_info.citylet district = res.result.ad_info.districtvm.setData({province: province,city: city,district: district,latitude: latitude,longitude: longitude})},fail: function (res) {console.log(res);},complete: function (res) {// console.log(res);}});} })
結果
總結
以上是生活随笔為你收集整理的小程序 获取当前用户城市信息(省市区)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】你没有变强是因为你一直很舒服
- 下一篇: 群体智能算法之蝙蝠算法