微信小程序 - 获取所在位置(省、市、区)

 

 

 

实现步骤

1. 获取当前经纬度

 

2. 调用腾讯(百度、高德)地图对应的请求地址,一般都会有独一的key, 譬如

 

腾讯地图调用地址:

1
https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${keys}

 

百度地图调用地址: 

1
https://apis.map.baidu.com/ws/geocoder/v2/?location=${latitude},${longitude}&key=${keys}

  

wxml

 

1
2
3
4
5
6
7
<view>{{district}}</view>
 
<picker mode="region" bindchange="bindRegionChange" value="{{region}}" custom-item="{{customItem}}">
  <view class="picker">
    当前选择:{{region[0]}} - {{region[1]}} - {{region[2]}}
  </view>
</picker>

 

 

js

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
let keys = 'SGXBZ-6X3K6-NYLSF-MALZD-QC6PK-BABOS';
let _page, _this;
 
Page({
 
  /**
   * 页面的初始数据
   */
  data: {
    customItem: '全部'
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    _this = this;
    wx.getLocation({
      success: function(res) {
        _this.getDistrict(res.latitude, res.longitude)
      },
    })
  },
 
 
  getDistrict(latitude, longitude) {
    _page = this;
    wx.request({
      url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${keys}`,
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log(res.data.result.address_component.district, res.data.result)
         
        // 省
        let province = res.data.result.address_component.province;
        // 市
        let city = res.data.result.address_component.city;
        // 区
        let district = res.data.result.address_component.district;
     
        _page.setData({
          district: res.data.result.address_component.district,
          region: [province,city,district]
        })
      }
    })
  },
 
  bindRegionChange (e) {
    console.log('picker发送选择改变,携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  }
})

 

  

 

posted @   Sunsin  阅读(15914)  评论(6编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
点击右上角即可分享
微信分享提示