微信小游戏里面获取当前位置,显示天气信息
通过微信 API wx.getLocation 获取当前位置的纬度和经度
示例代码:
wx.getLocation({
type: 'wgs84',
success: function(res) {
const latitude = res.latitude
const longitude = res.longitude
const speed = res.speed
const accuracy = res.accuracy
}
})
通过当前位置的纬度和经度在百度api获取当前位置信息
示例代码:
let xhr1 = new XMLHttpRequest();
let url1 = `http://api.map.baidu.com/geocoder/v2/?ak=r49Gt5U1GlgZVYOa6IoEMqZBQTHrLkYG&location=${latitude},${longitude}&output=json&pois=1`;
xhr1.onreadystatechange = function () {
if (xhr1.readyState == 4 && (xhr1.status >= 200 && xhr1.status < 400)) {
let response1 = xhr1.responseText;
let result = JSON.parse(response1);
console.log(response1);
console.log(result.status);
console.log(result.result);
city = result.result.addressComponent.city;
console.log('省区:'+city);
district = result.result.addressComponent.district;
console.log('县区:'+ district);
}
};
xhr1.open("GET", url1, true);
xhr1.send();
##通过中国万年历天气接口和城市信息获取天气信息
示例代码:
let xhr = new XMLHttpRequest();
let url = `http://wthrcdn.etouch.cn/weather_mini?city=${district}`;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
let response = xhr.responseText;
console.log(response);
let weatherInfo = JSON.parse(response);
console.log(weatherInfo.data.city);
console.log(weatherInfo.data.forecast);
forecast = weatherInfo.data.forecast;
}
};
xhr.open("GET", url, true);
xhr.send();
##结果图