每日前端
大道至简

微信小程序获取地理位置和天气

//index.js
//获取应用实例
const app = getApp()
Page({
data: {
weather: {
city: ”,
wea: ”,
tem: ”
}
},
/**
* 生命周期函数–监听页面显示
*/
onShow: function () {
this.getLocation()
},
// 第一次获取位置授权
getLocation: function () {
wx.getLocation({
type: ‘wgs84’,
success: (res) => {
const latitude = res.latitude
const longitude = res.longitude
this.getCity(latitude, longitude)
}
})
},
// 拒绝后再次点击地理授权
getLocationAuth: function () {
wx.getSetting({
success: (res) => {
if(res.authSetting[‘scope.userLocation’]==true){
this.getLocation()
}else{
wx.showModal({
title: `”五洲家园小区管家系统”需要获取您的地理位置`,
content: ‘您的位置信息将用于小程序位置展示’,
confirmText: ‘确定’,
confirmColor: ‘#3AC63A’,
cancelText: ‘取消’,
cancelColor: ‘#000000’,
success: function (res) {
if(res.confirm){
wx.openSetting({
success: () => {
this.getLocation()
},
fail: function () {
console.log(‘授权位置失败’)
}
})
}
if(res.cancel){
console.log(‘授权位置失败’)
}
}
})
}
}
})
},
// 获取城市名称
getCity: function (latitude, longitude) {
wx.request({
url: ‘http://api.map.baidu.com/geocoder/v2/?ak=D6WOzHaymzVVKvgiy8UbhQEznkgeK6BD&location=’ + latitude + ‘,’ + longitude + ‘&output=json’,
header: {
‘Content-Type’:’application/json’
},
success: (res) => {
const city =(res.data.result &&res.data.result.addressComponent.city)? res.data.result.addressComponent.city.replace(“市”,””):’广州’
this.getCityWeather(city)
}
});
},
// 获取城市天气
getCityWeather: function (city) {
wx.request({
url: ‘https://www.tianqiapi.com/api/’,
method: ‘GET’,
data: {
appid: 96227619,
appsecret: ‘XNH4SqHB’,
version: ‘v6’,
cityid: ”,
city: city,
ip: ”
},
success: (res) => {
const weather ={
city: res.data.city || ”,
wea: res.data.wea || ”,
tem: res.data.tem || ”
}
this.setData({
weather
})
},
fail: () => {
},
})
},
})
未经允许不得转载:每日前端 » 微信小程序获取地理位置和天气
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址