这次我要讲的是,如何在小程序中获取用户所在的位置,得到城市名。 在小程序中,有个api可以获取到用户的地理位置:

//在某个js里面
wx.getLocation({
type: 'wgs84', // 得到gps坐标
success:(res) => {
// 把得到的纬度经度传给下面的函数
this.getCity(res.latitude, res.longitude)
}
})
接下来是调用百度地图的api,进入百度地图开放平台,没有账户先注册一个,然后点击 “控制台”,然后点击 “创建运用”:




需要安装两个插件
npm install request --save // 安装request-promise之前需要安装这个
npm install request-promise --save
开始编写云函数:
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const rp = require('request-promise') // 引入request-promise插件
// 云函数入口函数
exports.main = async (event, context) => {
const res = await rp(`http://api.map.baidu.com/reverse_geocoding/v3/?ak=你的ak&output=json&coordtype=wgs84ll&location=${event.latitude},${event.longitude}`).then((res) => {
return res
})
return res // 将得到的结果返回给小程序端
}
这就是这个调用百度接口的云函数了,其中的event为小程序端调用云函数时传过来的参数,然后在小程序端,接上最开始的代码:
//在某个js里面
wx.getLocation({
type: 'wgs84', // 得到gps坐标
success:(res) => {
// 把得到的纬度经度传给下面的函数
this.getCity(res.latitude, res.longitude)
}
})
getCity(latitude, longitude) {
wx.cloud.callFunction({
name: '',//定义的云函数的名字
data: { // 传给云函数的参数对象,就是上面提到的event
latitude,
longitude
}
}).then((res) => { // res就是在云函数端返回的res
// 地理位置在res.result里面,请求过来是字符串,要先转成对象
console.log(JSON.parse(res.result).result)
})
}
来看一下打印出来是什么:
