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

 

 

实现步骤

1. 获取当前经纬度

 

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

腾讯地图调用地址:

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

百度地图调用地址: 

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

  

wxml

1 <view>{{district}}</view>

 

js

 1 let keys = 'SGXBZ-6X3K6-NYLSF-MALZD-QC6PK-BABOS';
 2 let _page, _this;
 3 
 4 Page({
 5 
 6   /**
 7    * 页面的初始数据
 8    */
 9   data: {
10 
11   },
12 
13   /**
14    * 生命周期函数--监听页面加载
15    */
16   onLoad: function(options) {
17     _this = this;
18     wx.getLocation({
19       success: function(res) {
20         _this.getDistrict(res.latitude, res.longitude)
21       },
22     })
23   },
24 
25 
26   getDistrict(latitude, longitude) {
27     _page = this;
28     wx.request({
29       url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${keys}`,
30       header: {
31         'Content-Type': 'application/json'
32       },
33       success: function(res) {
34         console.log(res.data.result.address_component.district, res.data.result)
35         _page.setData({
36           district: res.data.result.address_component.district
37         })
38       }
39     })
40   }
41 })

 

猜你喜欢

转载自www.cnblogs.com/cisum/p/9809993.html
今日推荐