作者:快乐的kang918_863 | 来源:互联网 | 2023-02-08 19:39
在前几篇(https://zhangphil.blog.csdn.net/article/details/110358440)的基础上,通过天气预报接口读取json天气预报数据,然后取出温度值,结合城市经纬度,最终通过folium绘制热力图。python代码如下:
import json
import webbrowser as wb
import pandas as pd
import urllib
import folium
from folium.plugins import HeatMap
import numpy as npdef get_weather_data(city_code):url = f'http://www.weather.com.cn/data/cityinfo/{city_code}.html'respOnse= urllib.request.urlopen(url)cOntent= response.read().decode('utf-8')return contentdef search_city_code(city_name):city_code = '-1'df = pd.read_json('city_code.json')for row in df.values:row_data = row[0]city_data = row_data['市']for cd in city_data:# print(cd['市名'], cd['编码'])if (city_name == cd['市名'] or cd['市名'] in city_name):city_code = cd['编码']breakreturn city_codeif __name__ == '__main__':city_name_list = ['北京', '上海', '广州', '深圳', '成都'] # 获取以上五个城市天气数据temp2 = []for cn in city_name_list:city_code = search_city_code(cn)weather_data = get_weather_data(city_code)json_data = json.loads(weather_data)t = json_data['weatherinfo']['temp2'].strip('℃') # 清洗数据,保留纯粹的数字temp2.append(float(t))print(temp2)latlngs = [[39.929986, 116.395645], # 北京中心点经纬度[31.249162, 121.487899], # 上海中心点经纬度[23.120049, 113.30765], # 广州中心点经纬度[22.546054, 114.025974], # 深圳中心点经纬度[30.679943, 104.067923]] # 成都中心点经纬度temp1_ = np.expand_dims(np.array(temp2), axis=0)temp1_np = temp1_.reshape((5, 1))data = np.concatenate((latlngs, temp1_np), axis=1)map = folium.Map([33., 113.], # 地图中心tiles='OpenStreetMap', # stamentonerzoom_start=5)HeatMap(data).add_to(map)map.save('m.html')wb.open('m.html')
绘制的热力图如下: