vue前端页面获取实时天气

该博客介绍了如何通过获取用户的IP地址,利用太平洋网络的IP查询接口和和风天气的API来实现实时天气的显示。首先获取用户省份和城市信息,然后调用和风天气的接口获取城市ID,最后获取并展示当前的温度和天气状况。在本地开发时通过vue.config.js配置接口转发,线上部署则借助nginx进行请求转发。

 首先获取用户定位的ip地址,我这边使用的是太平洋网络IP地址查询Web接口 (pconline.com.cn)

提供的接口,使用方法如下

<script>
    function testJson(obj) {
      sessionStorage.setItem('pro', obj.pro)
      sessionStorage.setItem('city', obj.city)
    }
  </script>
<script src="http://whois.pconline.com.cn/ipJson.jsp?callback=testJson"></script>

这时候我们已经获取到省份和地区市,我们可以通过存储的pro和city,注意实时和风天气必须要有开发者key

然后具体获取实时天气的,使用的是和风天气提供的接口开发文档 | 和风天气开发平台 (qweather.com)

getLocationId() {
    let param = {
    	key: defaultSettings.key,
		adm: sessionStorage.getItem('pro'),
		location: sessionStorage.getItem('city'),
	};
	getCity(param).then((res) => {
		if (res.code == 200) {
			this.locationId = res.location[0].id;
			this.getTem();
		}
	});
},
getTem() {
	let param = {
		key: defaultSettings.key,
		location: this.locationId,
	};
	getWeatehr(param).then((res) => {
		if (res.code == 200) {
			this.temp = res.now.temp
			this.temptext = res.now.text
			// this.weathericon = "qi-" + res.now.icon + '-fill'
			sessionStorage.setItem('temp', res.now.temp)
			sessionStorage.setItem('temptext', res.now.text)
		}
	});
},


/**
 * 获取城市id
 * @param {
 * key:'',
 * location:'绍兴',
 * adm:'浙江省'
 * } 
 * @returns 
 */
// export const getCity = p => get('https://geoapi.qweather.com/v2/city/lookup', p);

export const getCity = p => get('/qweather-city/v2/city/lookup', p);

/**
 * 获取天气
 * @param {
 *  key:'',
 * location:'101210507'
 * } 
 * @returns 
 */
// export const getWeatehr = p => get('https://devapi.qweather.com/v7/weather/now', p);

export const getWeatehr = p => get('/qweather-weather/v7/weather/now', p);

封装了它的接口,在本地使用,vue.config.js中配置并且转发使用

'/qweather-city': {
        target: 'https://geoapi.qweather.com',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/qweather-city': ''
        }
      },
      '/qweather-weather': {
        target: 'https://devapi.qweather.com',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/qweather-weather': ''
        }
}

getCity 方法获取到的是

上线时候,我使用的是ngnix转发,这样我们就能实时获取到天气内容啦

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值