一、用天气API(需要付费) 网址:https://www.tianqiapi.com/
请求方式及url:
请求方式:GET
接口地址:https://tianqiapi.com/free/day
请求示例
https://www.tianqiapi.com/free/day?appid=_____&appsecret=______
这里appid和APPScrect是两个必要参数,就是我们刚才控制台内记录下的个人的APPID和APPSecret
参数名 | 必选 | 类型 | 说明 | 备注(示例) |
appid | 是 | string | 用户appid | |
appsecret | 是 | string | 用户appsecret | |
version | 是 | string | 接口版本标识 | 固定值: v61 每个接口的version值都不一样 |
cityid | 否 | string | 城市ID | 请参考 城市ID列表 |
city | 否 | string | 城市名称 | 不要带市和区; 如: 青岛、铁西 |
province | 否 | string | 所在省 | 如果您担心city重名可传此参数, 不要带省和市; 如: 山东、上海 |
ip | 否 | string | IP地址 | 查询IP所在城市天气 |
lng | 否 | String | 经度 | 如: 119.545023 (需额外开通lbs权限, 500/年, 2000/5年) |
lat | 否 | String | 纬度 | 如: 36.044254 |
point | 否 | String | 坐标体系 | 默认百度坐标, 如使用高德坐标, 请传参: gaode |
callback | 否 | string | jsonp参数 | 如: jQuery.Callbacks |
vue | 否 | string | 跨域参数 | 如果您使用的是react、vue、angular请填写值: 1 |
unescape | 否 | Int | 是否转义中文 | 如果您希望json不被unicode, 直接输出中文, 请传此参数: 1 |
备注
cityid、city和ip参数3选一提交,如果不传,默认返回当前ip城市天气,cityid优先级最高。
二、PC项目 使用高德API 获取位置和天气信息
1.在高德地图上申请一个开发者,并且创建一个key 选择web端应用
2.在vue项目中的index.html中 使用script标签 引入生成的key和秘钥
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>你的项目名称</title>
</head>
<body>
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode:'你申请的安全秘钥',
}
</script>
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你申请的key"></script>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
3.在需要获取位置的页面中定义方法 使用citySearch和weather插件
4.可将获取到的天气信息保存至本地缓存再其他页面拉取渲染,注意要JSON.stringify 转化为JSON字符串,拉取的时候再用JSON.parse将JSON字符串转化为对象
getLngLatLocation() {
let that = this;
AMap.plugin("AMap.CitySearch", function () {
var citySearch = new AMap.CitySearch();
citySearch.getLocalCity(function (status, result) {
if (status === "complete" && result.info === "OK") {
// 查询成功,result即为当前所在城市信息
console.log("通过ip获取当前城市:", result);
AMap.plugin("AMap.Weather", function () {
//创建天气查询实例
var weather = new AMap.Weather();
//执行实时天气信息查询
weather.getLive(result.city, function (err, data) {
console.log("天气", data);
if (data) {
that.weather = data.weather;
that.temperature = data.temperature;
that.city = data.city;
let weatherObj = {
weather: data.weather,
temperature: data.temperature,
city: data.city,
};
localStorage.setItem(
"WEATHER_INFO",
JSON.stringify(weatherObj)
);
}else{
console.log(err);
}
});
});
}
});
});
},