持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情
大屏项目中,需要获取当前市天气预报的功能展示,因为对精确度要求不高,所以使用了以下比较简单的方法,方法如下:
一、根据ip获取地址
//引入搜狐API
<script typet="text/javascript" src="https://pv.sohu.com/cityjson?ie=utf-8"></script>
//使用
console.log(returnCitySN.cname); //浙江省杭州市
console.log(JSON.stringify(returnCitySN)); //{"cip":"122.234.58.159","cid":"330100","cname":"浙江省杭州市"}
缺点:
- 不能使用特定IP来查询,只能使用API原本查询的IP;
- 在服务器测试中,API直接查询出了服务器的IP,并不是用户的IP; 附:
- 搜狐IP地址查询接口(默认GBK):pv.sohu.com/cityjson
- 搜狐IP地址查询接口(可设置编码):pv.sohu.com/cityjson?ie…
- 搜狐另外的IP地址查询接口:txt.go.sohu.com/ip/soip
二、根据地址获取天气情况
//根据获取地址-浙江省杭州市
let reg = /.+?(省|市|区|州|盟|县|旗)/g;
let citys = returnCitySN.cname.match(reg)[1]
// 根据地址获取天气 - 本文使用Fetch发送get请求
fetch(`http://wthrcdn.etouch.cn/weather_mini?city=${citys}`)
.then(response => response.json())
.then(data =>{
A.db.weatherData = data.data.forecast[0].type
// console.log(data,data.data.forecast[0].type)
var data = null
if(weather === '晴'){
data = 1
}else if(weather === '多云'){
data = 2
}else if(weather.indexOf('雪') != -1){
// weather === '阵雪' || weather === '小雪' ||weather === '中雪' ||weather === '大雪'||weather === '暴雪' || weather === '小雪-中雪' || weather === '中雪-大雪' || weather === '大雪-暴雪'
data = 3
}else if(weather.indexOf('雨') != -1){
// weather === '雷阵雨' || weather ==="雷阵雨伴有冰雹" || weather ==='雨夹雪'|| weather === '小雨'|| weather ==='中雨'|| weather ==='大雨'||weather ==='暴雨'||weather ==='大暴雨'||weather ==='特大暴雨'||weather ==='冻雨'||weather ==='小雨-中雨'||weather ==='中雨-大雨'||weather ==='大雨-暴雨'||weather ==='暴雨-大暴雨'||weather ==='大暴雨-特大暴雨'
data = 4
}else{ //阴
data = 5
}
});