今天给大家讲一下小程序里面的定位,获取到用户所在城市,相信很多地方都用的到,已经很详细的把代码注释了,如
果又不懂的可以评论我,看到的话第一时间回复。
const app = getApp()
Page({
data: {
},
//事件处理函数
onLoad: function () {
var that = this;//获取当前指向
wx.showLoading({});//加载效果
wx.getStorage({//判断当前是否有本地存储,如果有执行success里的函数,否则执行getLocation方法
key: 'city',
success: function (res) {
var citycode = res.data.city;
that.setData({
currentCity: citycode
});
that.activitycontent();
},
fail: function () {
that.getLocation();
}
})
},
getLocation: function () {//获取到经纬度
var page = this
wx.getLocation({
type: 'wgs84',
success: function (res) {
var latitude = res.latitude
var longitude = res.longitude
page.loadCity(longitude, latitude)//已形参的方式传过去,执行loadCity方法
},
fail: function () {
wx.setStorage({
key: "city",
data: { 'city': '获取定位失败' }
})
page.setData({ currentCity: "获取定位失败" });
page.activitycontent();
}
})
},
loadCity: function (longitude, latitude) {//请求第三方服务器,转百度api
var page = this;
wx.request({
url: '后台接口',
data: { 'latitude': latitude, 'longitude': longitude, 'ak': '自己的ak' },
header: {
'Content-Type': 'application/json'
},
success: function (res) {
var city = res.data.result.addressComponent.city;//拿到获取到的城市
var city = city.replace('市', ' ');//我这边不需要市,所以就用字符串替换成 ‘ ’空了
page.setData({
currentCity: city
});
wx.setStorage({
key: "city",
data: { 'city': city }
})
page.activitycontent();
},
fail: function () {
page.setData({ currentCity: "获取定位失败" });
page.activitycontent();
},
})
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})