在微信小程序里自动获得当前手机所在的经纬度并转换成地址

举报
Jerry Wang 发表于 2021/12/22 22:38:17 2021/12/22
【摘要】 效果:我在手机上打开微信小程序,自动显示出我当前所在的地理位置:具体步骤:1. 使用微信jssdk提供的getLocation API拿到经纬度;2. 调用高德地图的api使用经纬度去换取地址的文字描述。wx.ready(() => {wx.getLocation({type: "gcj02",success: function(res) {var location ="&location=...

效果:我在手机上打开微信小程序,自动显示出我当前所在的地理位置:

具体步骤:

1. 使用微信jssdk提供的getLocation API拿到经纬度;

2. 调用高德地图的api使用经纬度去换取地址的文字描述。


wx.ready(() => {

wx.getLocation({

type: "gcj02",

success: function(res) {

var location =

"&location=" + res.longitude + "," + res.latitude;

ReservationService.getGeocode(location).then(response => {

if (

response.data.status === "1" &&

response.data.info === "OK"

) {

self.country =

response.data.regeocode.addressComponent.country;

self.city = response.data.regeocode.addressComponent.city;

var express =

"/" +

self.country +

"|" +

response.data.regeocode.addressComponent.province +

"|" +

self.city +

"|" +

response.data.regeocode.addressComponent.district +

"|" +

response.data.regeocode.addressComponent.township +

"/g";

self.address = response.data.regeocode.formatted_address.replace(

eval(express),

""

);

} else {

// get location error, plz input address

alert("无法获取地址信息,请稍后再试");

}

});

}

});

ReservationService.getGeocode的实现:

getGeocode(location) {

const key = ‘此处填入您高德地图app的key’;

return axios.post(‘https://restapi.amap.com/v3/geocode/regeo?key=’ + key + location);

}

看下面一个使用高德地图API将经纬度转换成文字描述的地址的例子,使用postman发送请求:

API响应:


{

"status": "1",

"regeocode": {

"addressComponent": {

"city": [],

"province": "北京市",

"adcode": "110101",

"district": "东城区",

"towncode": "110101001000",

"streetNumber": {

"number": "44号",

"location": "116.39795,39.9097239",

"direction": "东北",

"distance": "117.874",

"street": "广场东侧路"

},

"country": "中国",

"township": "东华门街道",

"businessAreas": [

{

"location": "116.3998109423077,39.90717459615385",

"name": "天安门",

"id": "110101"

},

{

"location": "116.39981058278138,39.92383706953642",

"name": "景山",

"id": "110101"

},

{

"location": "116.4118112683418,39.91461494422115",

"name": "王府井",

"id": "110101"

}

],

"building": {

"name": "天安门",

"type": "风景名胜;风景名胜相关;旅游景点"

},

"neighborhood": {

"name": [],

"type": []

},

"citycode": "010"

},

"formatted_address": "北京市东城区东华门街道天安门"

},

"info": "OK",

"infocode": "10000"

}

要获取更多Jerry的原创文章,请关注公众号"汪子熙"。

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。