好事成双,图层锁定轨迹追踪均完成

# coding=utf-8

import csv

import numpy as np
import folium
from folium import plugins
import csv
import requests
import json
import pandas as pd
import re
import time

import webbrowser




def PlotLineOnMap():
    Lat = []
    Lon = []
    Category = []
    Date_time = []
    print(type(Lat))
    fn = 'result.csv'
    with open(fn) as csvFile:
        csvDictReader = csv.DictReader(csvFile)
        for row in csvDictReader:
            print(row['lon'], row['lat'])
            Lat.insert(0,float(row['lat']))
            Lon.insert(0,float(row['lon']))
            Category.insert(0,str(row['category']))
            Date_time.insert(0,str(row['date_time']))
            print(Lat)


    # 给出的坐标系为GCJ-02,如果需要测试google地图,需要进行坐标转换

    tri = np.array(list(zip(Lat, Lon,Category,Date_time)))

    san_map = folium.Map(
        location=[36.641254, 117.068689],
        zoom_start=16,
        # 高德街道图
        tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
        # tiles='http://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', # 高德卫星图
        attr='default')

    layer_0329 = folium.FeatureGroup(name="0329")
    layer_0330 = folium.FeatureGroup(name="0330")
    layer_0331 = folium.FeatureGroup(name="0331")
    layer_0401 = folium.FeatureGroup(name="0401")


    #folium.PolyLine(tri, color='#3388ff').add_to(san_map)
  #  marker_cluster = plugins.MarkerCluster().add_to(san_map)
    for lat, lon,category,date_time in zip(Lat, Lon,Category,Date_time):
        print([category])
        print(type(category))
        print(category)
        print([date_time])

        if( date_time == '0329' ):
            if (category == '确诊者住址'):
                folium.Marker(location=[lat, lon], popup='Mt. Hood Meadows',
                              icon=folium.Icon(icon='cloud', color="red")).add_to(layer_0329)
            elif (category == '确诊者轨迹'):
                folium.Marker(location=[lat, lon], popup='Mt. Hood Meadows',
                              icon=folium.Icon(icon='cloud', color='orange')).add_to(layer_0329)









    san_map.add_child(layer_0329)
    san_map.add_child(layer_0330)
    san_map.add_child(layer_0331)
    san_map.add_child(layer_0401)





    san_map.add_child(folium.map.LayerControl())

    san_map.add_child(folium.LatLngPopup())
    san_map.save('test.html')


def main():
    num = 0
    y = []
    '''
    在url里key后面的******换为高德开放平台自己申请的key
    '''
    with open("地址.csv", 'r') as f:  # 写入将要转换的地址的文件路径,此处为默认文件路径(要先将文件提前导入)(注意是csv格式文件)
        r = csv.reader(f, delimiter=',')
        for row in r:
            print(row[0])
            print(row[1])
            url = "http://restapi.amap.com/v3/geocode/geo?key=831894c7f8fe1d2bedb982a040536650&address=" + row[2]
            dat = {
                'count': "1",
            }
            r = requests.post(url, data=json.dumps(dat))
            s = r.json()
            try:
                b = s['geocodes']
                text = str(b)
                print(text)
            except:
                text = 'none'

            # 省份
            try:
                pat1 = "'province': '(.*?)',"
                province = re.compile(pat1).findall(text)[0]
                print("省份:", province)
            except:
                province = 'none'
                print("省份:", province)

            # 城市
            try:
                pat2 = "'city': '(.*?)',"
                city = re.compile(pat2).findall(text)[0]
                print("城市:", city)
            except:
                city = 'none'
                print("城市:", city)

            # 区划
            try:
                pat3 = "'district': '(.*?)',"
                district = re.compile(pat3).findall(text)[0]
                print("区划:", district)
            except:
                district = 'none'
                print("区划:", district)

            # 经纬度
            try:
                pat4 = "'location': '(.*?)',"
                res3 = re.compile(pat4).findall(text)[0]
                # print(res3)
                lon_lat = res3.split(',')
                lon = float(lon_lat[0])
                lat = float(lon_lat[1])
                print("经度:", lon)
                print("纬度:", lat)
            except:
                lon = 'none'
                lat = 'none'
                print("经度:", lon)
                print("纬度:", lat)

            num += 1
            print("第" + str(num) + "条地址转换成功")
            print('**************************************')
            date_time =row[0]
            y.append([num,str(row[0]),row[1],row[2], province, city, district, lon, lat])
            result = pd.DataFrame(y)
            result.columns = ['num', 'date_time','category','address', 'province', 'city', 'district', 'lon', 'lat']
            result.to_csv('result.csv', encoding='gbk', index=False)
        print("全部地址转换成功")

    time.sleep(5)  #暂停10秒
    PlotLineOnMap()

    webbrowser.open('test.html')



if __name__ == '__main__':
    main()

你可能感兴趣的:(folium,folium)