folium 使用總結以及問題記錄
阿新 • • 發佈:2020-07-22
背景:工作需要使用地址範圍檔案中的經緯度連線在地圖上描繪出該範圍,並顯示給定地點資訊
模組選擇:folium,底圖豐富多樣,使用簡單易上手,建立互動式地圖
模組使用
1. 初始化一個map物件
# location 選定map的中心點座標 tiles 選擇底圖,不傳會使用預設底圖 """ # 高德底圖 tiles='http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7', # mapbox底圖 access_token需要自己去mapbox網站註冊獲取 tiles = "https://{s}.tiles.mapbox.com/v4/mapbox.emerald/{z}/{x}/{y}.png?access_token=sk.eyJ1IjoiaHVhbjEwMjEiLCJhIjoiY2tjb2ppeXpwMGxwZDJwcGJqNTh1MnBtaSJ9.NIAiFTr9VLiHMBy52Z_F9A" """ # zoom_start:地圖zoom的初始級別,預設為10。假設改成11的話,那麼就相當於在預設建立的地圖的級別上放大一級。 Map = folium.Map(location=map_settings.MID_LOCATION, zoom_start=10, tiles=map_settings.MAP_TILES, tiles='http://wprd02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7', attr='default' )
2. 使用Marker描點新增到地圖上,當點比較多時可以使用plugins.MarkerCluster()聚合,縮小後顯示數量,點選放大
folium.Marker([31.3255631839587,121.128785471592], popup=folium.Popup("地點資訊", max_width=1000)).add_to(Map) """ :param location: 座標 popup: 使用folium.Popup()渲染, Popup方法必傳顯示資訊,支援html,加上parse_html=True便會把原始內容當成普通字串來解析 icon: 可以使用folium.Icon() 渲染,更改顯示的樣式顏色,預設是水滴圖示 """
描點示例:
folium.Marker([34.343147, 108.939621], popup=folium.Popup("西安"), tooltip="click here").add_to(Map)
plugins.MarkerCluster()聚合示例:
3. Polygon 繪製多邊形填充地圖,也可以使用PolyLine 線段連線
- Polygon第一個引數為座標列表,popup同上
- color為多邊形邊線的顏色,fill_color表示填充的顏色, fillOpacity代表透明度
folium.Polygon(location, popup=folium.Popup(police_station[j], max_width=1000), tooltip='click here' , color=map_settings.fill_color.get(police_station[j]) , fill_color=map_settings.fill_color.get(police_station[j]) , fillOpacity=0.6 ).add_to(Map)
結果示例:
4. 完整程式碼
import os
import folium
import pandas as pd
import webbrowser as wb
from folium import plugins
import settings
class MapLocation:
def __init__(self, file_save_path):
# 描點連線範圍檔案
self.df = pd.read_json(settings.JSON_FILE_PATH)
# 需要展示的地址點
self.loc_df = pd.read_excel(settings.ADDR_FILE, header=None)
self.path = file_save_path
def main_map(self):
# 初始化
Map = folium.Map(location=settings.LOCATION,
zoom_start=10,
attr='default'
)
marker_cluster = plugins.MarkerCluster().add_to(Map)
for name, row in self.loc_df.iterrows():
folium.Marker([float(row[1].split(",")[0]), float(row[1].split(",")[1])],
popup=folium.Popup(row[0], max_width=1000)).add_to(marker_cluster)
locations = list(self.df["rings"])
station = list(self.df["station"])
for j in range(len(locations)):
# pandas讀出來是str不是list
str_loc = str(locations[j]).strip('[').strip("'").strip(']')
location = list()
for i in range(0, len(str_loc.split(';'))):
lat = str_loc.split(';')[i].split(',')[0].strip("'")
lon = str_loc.split(';')[i].split(',')[1].strip("'")
list1 = [float(lat), float(lon)]
location.append(list1)
folium.Polygon(location, popup=folium.Popup(station[j], max_width=1000), tooltip='click here'
, color=settings.fill_color.get(station[j])
, fill_color=settings.fill_color.get(station[j])
, fillOpacity=0.6
).add_to(Map)
Map.save(self.path)
wb.open(self.path)
if __name__ == '__main__':
map = MapLocation(r'd:\\test.html')
map.main_map()
問題記錄
模組bug,folium.py 檔案中_default_js中http://code.jquery.com/jquery-1.12.4.min.js 和https://rawcdn.githack.com/python-visualization/folium/master/folium/templates/leaflet.awesome.rotate.css 檔案無法訪問導致html渲染失敗,開啟頁面空白
解決方案:
- js檔案替換為可用的檔案,比如http://libs.baidu.com/jquery/2.0.0/jquery.min.js
- 註釋掉不可用的css檔案,暫時沒找到替代檔案