本人也是一个小白,第一次写文章,想锻炼一下自己,同时也记录一下自己在学习中解决的一些问题
在微信小程序中获取当前位置,用的是一个第三方的(聚合数据)api接口
第一步:在一个js中封装一个函数
export function getCurrentLocation(){return new Promise(function(resolve,reject){wx.getLocation({success: function (res) {wx.request({url: `http://apis.juhe.cn/geo/?key=自己的APPKEY&lat=${res.latitude}&lng=${res.longitude}&type=1`,success: function (data) {// console.log(data)resolve(data)}})
},})})}第二步:导入到需要用这个函数的页面的js中
import { getCurrentLocation} from "../../utils/api.js"Page({
/** * 页面的初始数据 */ data: { address:"定位中" },第三步:
* 生命周期函数--监听页面初次渲染完成 */ onReady: function () { var that = this; getCurrentLocation().then(function(data){ // console.log(data) that.setData({ address:data.data.result.address }) }) },第四步:渲染到页面中
<view class='top-left'>
{{address}}
</view>