首先获取用户定位的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转发,这样我们就能实时获取到天气内容啦

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐