背景:工作需要使用地址范圍文件中的經緯度連線在地圖上描繪出該范圍,並顯示給定地點信息
模塊選擇: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()
問題記錄
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文件,暫時沒找到替代文件