微信小程序--获取用户地理位置名称(无须用户授权)的方法

准备

1、在http://lbs.qq.com/网站申请key

2、在微信小程序后台把apis.map.qq.com添加进request合法域名

效果

 

 

添加封装

 
/**
 * 发起网络请求
 * @param {string} url
 * @param {object} params
 * @return {Promise}
 */
 static request(url, params, method = "GET", type = "json") {
 console.log("向后端传递的参数", params);
 return new Promise((resolve, reject) => {
  let opts = {
  url: url,
  data: Object.assign({}, params),
  method: method,
  header: { 'Content-Type': type },
  success: resolve,
  fail: reject
  }
  // console.log("请求的URL", opts.url);
  wx.request(opts);
 });
 };
 /**
 * 获取用户中心位置经纬度
 * @param {ctx} name
 */
 static getCenterLocation(name) {
 return new Promise((resolve, reject) => name.getCenterLocation({ success: resolve, fail: reject }));
 }

 

如果已经存在,则不用添加

js

let app = getApp();
let wechat = require("../../utils/wechat");
Page({
 onReady(e) {
 let mapCtx = wx.createMapContext('myMap');
 setTimeout(() => {
  mapCtx.moveToLocation();
 }, 1000);
 setTimeout(() => {
  this.getAddress(mapCtx);
 }, 2000);
 },
 getAddress(mapCtx) {
 wechat.getCenterLocation(mapCtx)
  .then(d => {
  console.log(d);
  let { latitude, longitude } = d;
  console.log("当前位置纬度", latitude, "当前位置经度", longitude);
  let url = `https://apis.map.qq.com/ws/geocoder/v1/`;
  let key = 'XXXXX-D6FAD-RSG4U-HBE6F-NVFNK-XXXXX';
  let params = {
   location: latitude + "," + longitude,
   key
  }
  return wechat.request(url, params);
  })
  .then(d => {
  console.log(d);
  console.log("当前地址", d.data.result.address);
  })
  .catch(e => {
  console.log(e);
  })
 }
  
})

 

html

<map id="myMap" show-location="true" scale="16" />

 

转载于:https://www.cnblogs.com/plBlog/p/11454235.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值