要将CSV文件导出到自定义地图,您需要执行以下步骤:
以下是一个简单的示例,展示如何使用Python读取CSV文件,并使用Leaflet.js将数据导出到HTML地图中。
import csv
# 读取CSV文件
data = []
with open('data.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
# 生成HTML文件
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>Custom Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<style>
#map { height: 600px; }
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var markers = L.markerClusterGroup();
{markers_html}
markers.addTo(map);
</script>
</body>
</html>
"""
# 生成标记HTML
markers_html = ""
for item in data:
lat = item['latitude']
lon = item['longitude']
popup_content = f"<h3>{item['name']}</h3><p>{item['description']}</p>"
markers_html += f"""
L.marker([{lat}, {lon}]).bindPopup("{popup_content}").addTo(markers);
"""
# 写入HTML文件
with open('map.html', 'w') as htmlfile:
htmlfile.write(html_content)
<!DOCTYPE html>
<html>
<head>
<title>Custom Map</title>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<style>
#map { height: 600px; }
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var markers = L.markerClusterGroup();
// 标记数据将通过Python脚本动态生成
markers.addTo(map);
</script>
</body>
</html>
通过以上步骤和示例代码,您可以将CSV文件中的数据导出到自定义地图中,并进行可视化展示。
领取专属 10元无门槛券
手把手带您无忧上云