(1)通过百度地图开放平台将地址转换为经纬度:
https://api.map.baidu.com/geocoding/v3/?address={江苏省连云港市江苏海洋大学苍梧校区}&output=json&ak=
import requests
import xlwt
import pandas as pd
import numpy as np
from tqdm import tqdm
def transform(address, ak):
url = 'http://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=%s'%(address, ak)
response = requests.get(url)
if response.status_code == 200:
response_json = response.json()
if response_json['status'] == 0:
data = {'address': address, 'lng': response_json['result']['location']['lng'], 'lat': response_json['result']['location']['lat']}
else:
data = None
return data
else:
print('%s 地址转换经纬度失败'%address)
print(transform('江苏海洋大学', '你的ak'))
(2)读取CSV文件
book = pd.read_csv('data/急救中心综合业务信息查询.csv')
addresses = book['发病地址'].values.tolist()
districts = book['呼叫区域'].values.tolist()
(3)批量转换并保存至CSV
def batch_transform_and_save(prefix, districts, addresses, ak, save_path):
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet("Sheet1", cell_overwrite_ok=True)
sheet.write(0, 0, '地址')
sheet.write(0, 1, '经度')
sheet.write(0, 2, '纬度')
length = len(addresses)
for i in tqdm(range(0, length)):
address = str(prefix)
if districts[i] == '市辖区':
address = address + str(addresses[i])
else:
address = address + str(addresses[i]) + str(districts[i])
transformed_address = transform(address, ak)
if transformed_address == None:
continue
sheet.write(i+1, 0, transformed_address['address'])
sheet.write(i+1, 1, transformed_address['lng'])
sheet.write(i+1, 2, transformed_address['lat'])
book.save(save_path)
batch_transform_and_save('江苏省连云港市', addresses, districts, ak, 'data/发病地址数据集.csv')
(4)folium生成热力图
import folium
from folium.plugins import HeatMap
location_book = pd.read_csv('data/发病地址数据集.csv')
lng = location_book['经度'].values.tolist()
lat = location_book['纬度'].values.tolist()
data = []
for i in range(0, len(lng)):
temp = []
temp.append(lat[i])
temp.append(lng[i])
temp.append(0.1)
data.append(temp)
mp = folium.Map(location=[119.188671, 34.612552], zoom_start=14)
HeatMap(data[0:400]).add_to(mp)
mp.save('./Heatmap.html')
|