Python輕松實現(xiàn)某德地圖可視化功能
更新時間:2026年01月05日 09:06:33 作者:大數(shù)據(jù)自動化RPA
文章介紹了如何使用Python輕松實現(xiàn)某德地圖的可視化,并提供了兩種解決方案:一種是生成本地網(wǎng)頁,另一種是生成服務(wù)器網(wǎng)頁的改進版,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
Python輕松實現(xiàn)某德地圖可視化,直接給出解決方案
一.、生成網(wǎng)頁
import pandas as pd
import folium
from folium import plugins
import random
# 模擬數(shù)據(jù)生成
def generate_mock_data():
# 生成模擬景點數(shù)據(jù)
locations = []
base_lat = 23.122373
base_lon = 113.268027
# 生成100個隨機景點數(shù)據(jù)
for i in range(100):
# 在基礎(chǔ)坐標附近生成隨機偏移
lat = base_lat + random.uniform(-0.1, 0.1)
lon = base_lon + random.uniform(-0.1, 0.1)
locations.append({'lat': lat, 'lon': lon})
return pd.DataFrame(locations)
# 使用模擬數(shù)據(jù)替代CSV讀取
data = generate_mock_data()
# 創(chuàng)建地圖,使用高德地圖底圖(正確配置attribution)
heatmap1 = folium.Map(
location=[23.122373, 113.268027],
zoom_start=10,
control_scale=True,
tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
attr='© <a rel="external nofollow" rel="external nofollow" rel="external nofollow" >高德地圖</a>'
)
# 添加中心標記
folium.Marker(
[23.122373, 113.268027],
popup='<i>J哥</i>',
icon=folium.Icon(icon='cloud', color='green')
).add_to(heatmap1)
# 檢查數(shù)據(jù)中是否存在lat和lon列
if 'lat' in data.columns and 'lon' in data.columns:
# 創(chuàng)建熱力圖數(shù)據(jù)
heat_data = [[row["lat"], row["lon"]] for index, row in data.iterrows()]
# 添加熱力圖層
heatmap_layer = plugins.HeatMap(heat_data)
heatmap1.add_child(heatmap_layer)
else:
print("錯誤:數(shù)據(jù)中缺少lat或lon列")
print("數(shù)據(jù)列名:", data.columns.tolist())
# 保存地圖
heatmap1.save("folium_map1.html")
print("地圖已保存為 folium_map1.html")
print(f"使用了 {len(data)} 個模擬數(shù)據(jù)點")
from pathlib import Path
# 路徑配置
BASE_DIR = Path(__file__).parent # 腳本所在目錄
DB_DIR = BASE_DIR / '圖樣'
DB_DIR.mkdir(exist_ok=True)
HTML_FILE_PATH = DB_DIR / "002.html" # 明確HTML文件完整路徑
# 保存地圖
heatmap1.save(DB_DIR /"folium_map1.html")
print("地圖已保存為 folium_map1.html")
print(f"使用了 {len(data)} 個模擬數(shù)據(jù)點")



二、生成服務(wù)器網(wǎng)頁
import pandas as pd
import folium
from folium import plugins
import random
from nicegui import ui
import os
import webbrowser
from pathlib import Path
# 模擬數(shù)據(jù)生成
def generate_mock_data():
# 生成模擬景點數(shù)據(jù)
locations = []
base_lat = 23.122373
base_lon = 113.268027
# 生成100個隨機景點數(shù)據(jù)
for i in range(100):
# 在基礎(chǔ)坐標附近生成隨機偏移
lat = base_lat + random.uniform(-0.1, 0.1)
lon = base_lon + random.uniform(-0.1, 0.1)
locations.append({'lat': lat, 'lon': lon})
return pd.DataFrame(locations)
# 生成熱力圖HTML
def generate_heatmap_html():
data = generate_mock_data()
# 創(chuàng)建地圖,使用高德地圖底圖
heatmap1 = folium.Map(
location=[23.122373, 113.268027],
zoom_start=10,
control_scale=True,
tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
attr='© <a rel="external nofollow" rel="external nofollow" rel="external nofollow" >高德地圖</a>'
)
# 添加中心標記
folium.Marker(
[23.122373, 113.268027],
popup='<i>J哥</i>',
icon=folium.Icon(icon='cloud', color='green')
).add_to(heatmap1)
# 檢查數(shù)據(jù)中是否存在lat和lon列
if 'lat' in data.columns and 'lon' in data.columns:
# 創(chuàng)建熱力圖數(shù)據(jù)
heat_data = [[row["lat"], row["lon"]] for index, row in data.iterrows()]
# 添加熱力圖層
heatmap_layer = plugins.HeatMap(heat_data)
heatmap1.add_child(heatmap_layer)
else:
print("錯誤:數(shù)據(jù)中缺少lat或lon列")
print("數(shù)據(jù)列名:", data.columns.tolist())
# 保存地圖到臨時文件
temp_file = 'temp_heatmap.html'
heatmap1.save(temp_file)
return temp_file
# 創(chuàng)建NiceGUI界面
@ui.page('/')
def main():
ui.label('熱力圖可視化').classes('text-2xl font-bold')
# 生成熱力圖按鈕
def show_heatmap():
html_file = generate_heatmap_html()
# 在新標簽頁中打開熱力圖
webbrowser.open(f'file://{os.path.abspath(html_file)}')
ui.notify(f'熱力圖已生成并打開: {html_file}')
ui.button('生成并查看熱力圖', on_click=show_heatmap).classes('mt-4')
# 顯示數(shù)據(jù)信息
data = generate_mock_data()
ui.label(f'模擬數(shù)據(jù)點數(shù)量: {len(data)}').classes('mt-4')
# 顯示前幾行數(shù)據(jù)
ui.label('前5行數(shù)據(jù)預(yù)覽:').classes('mt-4')
# 使用正確的ui.table語法
columns = [
{'name': 'index', 'label': 'Index', 'field': 'index'},
{'name': 'lat', 'label': '緯度', 'field': 'lat'},
{'name': 'lon', 'label': '經(jīng)度', 'field': 'lon'}
]
rows = [{'index': i, 'lat': row['lat'], 'lon': row['lon']} for i, (idx, row) in enumerate(data.head().iterrows())]
ui.table(columns=columns, rows=rows).classes('w-full')
# 啟動應(yīng)用
if __name__ in {"__main__", "__mp_main__"}:
ui.run(title='熱力圖可視化應(yīng)用', port=8080, reload=True)改進版
import pandas as pd
import folium
from folium import plugins
import random
from nicegui import ui
import os
import webbrowser
from pathlib import Path
import numpy as np
import base64
from io import BytesIO
# 模擬數(shù)據(jù)生成
def generate_mock_data():
# 生成模擬景點數(shù)據(jù)
locations = []
base_lat = 23.122373
base_lon = 113.268027
# 生成100個隨機景點數(shù)據(jù)
for i in range(100):
# 在基礎(chǔ)坐標附近生成隨機偏移
lat = base_lat + random.uniform(-0.1, 0.1)
lon = base_lon + random.uniform(-0.1, 0.1)
# 生成隨機數(shù)值用于條形圖高度和顏色
value = random.uniform(1, 100)
locations.append({'lat': lat, 'lon': lon, 'value': value})
return pd.DataFrame(locations)
# 生成熱力圖HTML并轉(zhuǎn)換為base64
def generate_heatmap_base64():
data = generate_mock_data()
# 創(chuàng)建地圖,使用高德地圖底圖
heatmap1 = folium.Map(
location=[23.122373, 113.268027],
zoom_start=10,
control_scale=True,
tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
attr='© <a rel="external nofollow" rel="external nofollow" rel="external nofollow" >高德地圖</a>',
# 設(shè)置地圖背景為藍紫色
style='background-color: #4B0082;'
)
# 添加中心標記
folium.Marker(
[23.122373, 113.268027],
popup='<i>J哥</i>',
icon=folium.Icon(icon='cloud', color='green')
).add_to(heatmap1)
# 為每個點添加七彩條形圖(使用SVG圖形)
for idx, row in data.iterrows():
# 創(chuàng)建SVG條形圖元素
svg_bar_html = create_svg_bar(row['value'])
# 計算條形圖尺寸(長度變?yōu)樵瓉淼牧叮瑢挾葹樵瓉淼乃姆种唬?
bar_width = 9 # 5 + 2*2 (原始寬度 + 兩邊邊框)
bar_height = max(int(row['value'] / 5) * 6, 30) + 4 # 高度變?yōu)樵瓉淼牧?+ 兩邊邊框
if bar_height < 34: # 最小高度調(diào)整
bar_height = 34
icon = folium.DivIcon(
html=svg_bar_html,
icon_size=(bar_width, bar_height),
icon_anchor=(bar_width // 2, bar_height // 2) # 錨點設(shè)置
)
# 在地圖上添加標記
folium.Marker(
[row['lat'], row['lon']],
icon=icon,
popup=f"數(shù)值: {row['value']:.2f}"
).add_to(heatmap1)
# 添加顏色條例圖
add_smooth_color_legend(heatmap1)
# 將地圖保存為HTML字符串
map_html = heatmap1._repr_html_()
return map_html
# 創(chuàng)建SVG條形圖
def create_svg_bar(value):
# 計算條形圖尺寸(長度變?yōu)樵瓉淼牧?,寬度為原來的四分之一?
width = 5 # 20 / 4
height = max(int(value / 5) * 6, 30) # 高度變?yōu)樵瓉淼牧?
border_width = 2 # 黃色邊框?qū)挾?
svg_width = width + 2 * border_width
svg_height = height + 2 * border_width
# 創(chuàng)建漸變定義
gradient_id = f"grad_{int(value * 100)}"
# 生成漸變色條
gradient_html = f'''
<svg width="{svg_width}" height="{svg_height}" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="{gradient_id}" x1="0%" y1="100%" x2="0%" y2="0%">
'''
# 添加漸變停止點
num_steps = 20
for i in range(num_steps + 1):
stop_value = (i / num_steps) * value
color = get_smooth_color_by_value(stop_value)
offset = i / num_steps
gradient_html += f'<stop offset="{offset * 100}%" stop-color="{color}" />\n'
gradient_html += f'''
</linearGradient>
</defs>
<rect x="{border_width}" y="{border_width}" width="{width}" height="{height}"
fill="url(#{gradient_id})" stroke="yellow" stroke-width="{border_width}"/>
</svg>
'''
return gradient_html
# 根據(jù)數(shù)值映射平滑顏色
def get_smooth_color_by_value(value):
# 歸一化數(shù)值到0-1范圍
normalized_value = min(max(value / 100.0, 0), 1)
# 定義彩虹色譜的關(guān)鍵點
hue = normalized_value * 300 # 0-300度的色相范圍(避免紅色重復(fù))
# 將HSV轉(zhuǎn)換為RGB
h = hue / 60.0
c = 1.0 # 飽和度
x = c * (1 - abs(h % 2 - 1))
if 0 <= h < 1:
r, g, b = c, x, 0
elif 1 <= h < 2:
r, g, b = x, c, 0
elif 2 <= h < 3:
r, g, b = 0, c, x
elif 3 <= h < 4:
r, g, b = 0, x, c
elif 4 <= h < 5:
r, g, b = x, 0, c
else:
r, g, b = c, 0, x
# 轉(zhuǎn)換為0-255范圍
r = int(r * 255)
g = int(g * 255)
b = int(b * 255)
# 轉(zhuǎn)換為十六進制
return f'#{r:02x}{g:02x}{b:02x}'
# 添加平滑顏色條例圖
def add_smooth_color_legend(m):
# 創(chuàng)建顏色條的HTML(長度變?yōu)樵瓉淼牧?,寬度為原來的四分之一?
legend_html = '''
<div style="
position: fixed;
bottom: 50px;
right: 50px;
z-index:9999;
background-color: white;
padding: 10px;
border:2px solid grey;
border-radius: 5px;
font-size: 14px;
box-shadow: 0 0 10px rgba(0,0,0,0.2);
">
<p style="text-align: center; margin: 0 0 10px 0;"><b>數(shù)值范圍</b></p>
<div style="display: flex; flex-direction: column; height: 900px; width: 7.5px; margin: 0 auto;">
'''
# 生成漸變色條(長度變?yōu)樵瓉淼牧叮?
for i in range(100, 0, -1): # 從100到1
color = get_smooth_color_by_value(i)
legend_html += f'<div style="height: 9px; background-color: {color}; border: 0.5px solid black;"></div>' # 1.5px * 6
legend_html += '''
</div>
<div style="display: flex; justify-content: space-between; margin-top: 10px;">
<span>0</span>
<span>50</span>
<span>100</span>
</div>
</div>
'''
m.get_root().html.add_child(folium.Element(legend_html))
# 創(chuàng)建NiceGUI界面
@ui.page('/')
def main():
ui.label('拉長版平滑過渡七彩條形圖').classes('text-2xl font-bold')
# 顯示地圖
def show_map():
map_html = generate_heatmap_base64()
# 使用ui.html顯示地圖,添加sanitize=False參數(shù)
ui.html(map_html, sanitize=False).classes('w-full h-screen')
# 顯示地圖按鈕
ui.button('顯示地圖', on_click=show_map).classes('mt-4')
# 顯示數(shù)據(jù)信息
data = generate_mock_data()
ui.label(f'模擬數(shù)據(jù)點數(shù)量: {len(data)}').classes('mt-4')
# 顯示前幾行數(shù)據(jù)
ui.label('前5行數(shù)據(jù)預(yù)覽:').classes('mt-4')
# 使用正確的ui.table語法
columns = [
{'name': 'index', 'label': 'Index', 'field': 'index'},
{'name': 'lat', 'label': '緯度', 'field': 'lat'},
{'name': 'lon', 'label': '經(jīng)度', 'field': 'lon'},
{'name': 'value', 'label': '數(shù)值', 'field': 'value'}
]
rows = [{'index': i, 'lat': row['lat'], 'lon': row['lon'], 'value': row['value']} for i, (idx, row) in enumerate(data.head().iterrows())]
ui.table(columns=columns, rows=rows).props('dense flat bordered').classes('w-full')
# 啟動應(yīng)用
if __name__ in {"__main__", "__mp_main__"}:
ui.run(title='拉長版平滑過渡七彩條形圖應(yīng)用', port=8080, reload=False)

到此這篇關(guān)于Python輕松實現(xiàn)某德地圖可視化功能的文章就介紹到這了,更多相關(guān)python地圖可視化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python實現(xiàn)解析Bit Torrent種子文件內(nèi)容的方法
這篇文章主要介紹了Python實現(xiàn)解析Bit Torrent種子文件內(nèi)容的方法,結(jié)合實例形式分析了Python針對Torrent文件的讀取與解析相關(guān)操作技巧與注意事項,需要的朋友可以參考下2017-08-08
Python實現(xiàn)在PDF中插入單圖像水印和平鋪圖像水印
這篇文章主要為大家詳細介紹了如何使用Python實現(xiàn)在PDF中插入單圖像水印和平鋪圖像水印,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-04-04
python 項目目錄結(jié)構(gòu)設(shè)置
JAVA有標準的maven目錄結(jié)構(gòu),golang也有建議的目錄結(jié)構(gòu),那么我想python是不是也有一個比較好的目錄結(jié)構(gòu)組織方式呢2020-02-02
基于Python實現(xiàn)Excel轉(zhuǎn)Markdown表格
Markdown(也簡稱md)作為一種輕量級標記語言,因其易寫易讀,效果美觀大方,不僅被眾多網(wǎng)站使用,也是程序員們做筆記、寫文檔的首選。本文將利用Python實現(xiàn)Excel轉(zhuǎn)Markdown表格,感興趣的可以了解一下2022-04-04

