小程序获取当前位置所在的城市

本文介绍如何在微信小程序中实现地理位置定位功能,包括申请开发者密钥、配置安全域名、使用JavaScript SDK及权限管理等步骤。

1、话不多说,直接上干货

先来张目录结构

① index.wxml

<view class="retailStore">
   <view class="cnaps  borderBottom">
    <text>所在城市:</text>
    <text class='m-bbt'>{{province}} {{city}}</text>
  </view>
</view>

②index.js

插入提示:

1. 申请开发者密钥(key):申请密钥

2. 下载微信小程序JavaScriptSDK,微信小程序JavaScriptSDK v1.0           下载完成后放入utils文件夹下引用即可

3. 安全域名设置,在“设置” -> “开发设置”中设置request合法域名,添加https://apis.map.qq.com

测试用的话可以在微信开发工具中选择详情,如下图

//index.js
//获取应用实例
const app = getApp();
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk;
Page({
  data: {
    province: '',
    city: '',
    latitude: '',
    longitude: ''
  },
  onLoad: function () {
    qqmapsdk = new QQMapWX({
      key: 'xxxx-xxxx-xxxx-xxxx' //自己的key秘钥 http://lbs.qq.com/console/mykey.html 在这个网址申请
    });
  },
  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);
      }
    });
  }
})

效果图:

谢谢观看,随便转载!!~~~(任性 蜜汁微笑)

仓库地址:项目地址

### 微信小程序获取当前位置城市名称API 在微信小程序中,通过`uni.getLocation()`可以获取用户的地理位置信息。然而,在成功回调函数中的返回数据仅包含经纬度信息,而具体的地址描述则不在其中[^1]。 对于希望获得更详尽的地理信息(如城市名),开发者需进一步调用腾讯地图提供的逆地址解析服务接口来完成这一目标。下面是一个完整的解决方案: #### 配置权限 确保已为应用请求了必要的定位权限。这一步骤是在项目的`manifest.json`文件内的`permission`部分进行设置。 #### 获取并处理位置信息 ```javascript // 调用getLocation方法得到经纬度 uni.getLocation({ type: 'wgs84', success(res) { const latitude = res.latitude; const longitude = res.longitude; // 使用腾讯地图SDK或其他方式发起反向编码请求 uni.request({ url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=YOUR_API_KEY`, method: 'GET', success(response){ console.log('City:', response.data.result.address_component.city); }, fail(err){ console.error('Failed to get city name', err); } }); }, fail(error){ console.error('Location permission denied or failed.', error); } }); ``` 此代码片段展示了如何先利用`uni.getLocation()`取得用户所在地点的坐标,再借助腾讯地图开放平台所提供的Web Service API实现从这些坐标到实际地名之间的转换过程[^3]。 请注意替换上述URL中的`YOUR_API_KEY`为你自己的腾讯地图API密钥,并且考虑到隐私政策的要求以及用户体验的影响因素,在收集任何个人敏感信息之前应当充分告知用户并将同意机制纳入考虑范围之内。
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值