获取当前位置的天气情况
1.获取当前省市的位置
根据腾讯地图api获取当地位置信息
定位服务-IP定位-官方文档:https://lbs.qq.com/service/webService/webServiceGuide/position/webServiceIp
如何成为开发者并创建 Key:https://lbs.qq.com/mobile/androidMapSDK/developerGuide/getKey
$.ajax({
type: "get", //接口规定,只能用get
async: true, //异步
url: "https://apis.map.qq.com/ws/location/v1/ip", //地理位置信息的接口接口地址
data: {
key: "45IBZ-GQG3B-TZ5UV-JCW3H-****-****",
output: "jsonp",
}, //参数格式必须用到output传参为jsonp,否则会报跨域问题
dataType: "jsonp", //跨域,必须用到jsonp
success: (res) => {
console.log("res :>> ", res);
var adcode = res.result.ad_info.adcode;
// 根据城市,获取当地天气和时间
this.getLocalWeather(adcode); // 调用获取天气方法
return res;
},
error: (XMLHttpRequest, textStatus, errorThrown) => {
console.log(XMLHttpRequest);
},
});
2.获取当前位置天气情况
拿到当前位置后,根据高德开放平台api进行天气查询
天气查询-官方文档:https://lbs.amap.com/api/webservice/guide/api/weatherinfo
如何成为开发者并创建 Key:https://lbs.amap.com/api/webservice/create-project-and-key
如果接口调试失败,可通过官网错误码说明来查看具体哪项配置错误进行修改
$.ajax({
type: "get", //接口规定,只能用get
async: true, //异步
url: "https://restapi.amap.com/v3/weather/weatherInfo", //接口地址
data: {
key: "9a579ab863471c25f4da54ed********",
city: adcode,
extensions: "all",
output: "jsonp",
}, //参数格式必须用到output传参为jsonp,否则会报跨域问题
dataType: "jsonp", //跨域,必须用到jsonp
success: (res) => {
console.log("res :>> ", res);
// 获取当天数据
let todayWeather = res.forecasts[0].casts[0];
if (todayWeather) {
var weather = todayWeather.dayweather;
}
return res;
},
error: (XMLHttpRequest, textStatus, errorThrown) => {
console.log(XMLHttpRequest);
},
});
3.完整代码
//获取当前省市的位置
getLocalCity() {
$.ajax({
type: "get", //接口规定,只能用get
async: true, //异步
url: "https://apis.map.qq.com/ws/location/v1/ip", //地理位置信息的接口接口地址
data: {
key: "45IBZ-GQG3B-TZ5UV-JCW3H-****-****",
output: "jsonp",
}, //参数格式必须用到output传参为jsonp,否则会报跨域问题
dataType: "jsonp", //跨域,必须用到jsonp
success: (res) => {
console.log("res :>> ", res);
var city = res.result.ad_info.adcode;
// 根据城市,获取当地天气和时间
this.getLocalWeather(city); // 调用获取天气方法
return res;
},
error: (XMLHttpRequest, textStatus, errorThrown) => {
console.log(XMLHttpRequest);
},
});
},
//获取当前位置天气情况
getLocalWeather(city) {
if (city && city !== "") {
$.ajax({
type: "get", //接口规定,只能用get
async: true, //异步
url: "https://restapi.amap.com/v3/weather/weatherInfo", //接口地址
data: {
key: "9a579ab863471c25f4da54ed********",
city: city,
extensions: "all",
output: "jsonp",
}, //参数格式必须用到output传参为jsonp,否则会报跨域问题
dataType: "jsonp", //跨域,必须用到jsonp
success: (res) => {
console.log("res :>> ", res);
// 获取当天数据
let todayWeather = res.forecasts[0].casts[0];
if (todayWeather) {
var weather = todayWeather.dayweather;
}
return res;
},
error: (XMLHttpRequest, textStatus, errorThrown) => {
console.log(XMLHttpRequest);
},
});
}
},