json文件为{"y":115.9053400,"x":29.1660400,"label":0},用flask和leaflet画聚类图
时间: 2023-10-10 10:06:25 浏览: 98
首先,需要安装Flask和Leaflet的相关库。可以在命令行窗口中使用以下命令安装:
```bash
pip install flask
pip install folium
```
接下来,创建一个名为app.py的Python文件,编写以下代码:
```python
from flask import Flask, render_template
import json
import folium
import pandas as pd
app = Flask(__name__)
@app.route('/')
def home():
return render_template('map.html')
@app.route('/data')
def data():
data = [{"y":115.9053400,"x":29.1660400,"label":0},
{"y":115.9099600,"x":29.1616200,"label":2},
{"y":115.9068700,"x":29.1703400,"label":1},
{"y":115.9029900,"x":29.1684600,"label":0},
{"y":115.9112000,"x":29.1726600,"label":1},
{"y":115.8998800,"x":29.1575800,"label":2},
{"y":115.9089800,"x":29.1664100,"label":2},
{"y":115.9078600,"x":29.1769300,"label":1},
{"y":115.9019000,"x":29.1758000,"label":2},
{"y":115.9081800,"x":29.1632600,"label":0}]
return json.dumps(data)
if __name__ == '__main__':
app.run(debug=True)
```
该代码定义了一个名为app的Flask应用程序。它有两个路由:/和/data。当用户访问/路由时,应用程序将渲染名为map.html的HTML模板。当用户访问/data路由时,应用程序将返回一个JSON格式的数据,用于在地图上绘制聚类图。
接下来,创建一个名为map.html的HTML模板,编写以下代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Clustering Map</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0/leaflet.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0/leaflet.js"></script>
<style>
#map {
height: 500px;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([29.1660400, 115.9053400], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
'<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
id: 'mapbox.streets'
}).addTo(map);
var markers = L.markerClusterGroup();
fetch('/data')
.then(response => response.json())
.then(data => {
for (var i = 0; i < data.length; i++) {
var marker = L.marker([data[i].x, data[i].y]);
markers.addLayer(marker);
}
map.addLayer(markers);
});
</script>
</body>
</html>
```
该代码定义了一个HTML模板,其中包含一个id为map的div元素,用于显示地图。它还包含一些JavaScript代码,用于使用Leaflet库绘制地图和聚类标记。它还从/data路由获取JSON数据,并将其用于绘制聚类标记。
最后,打开命令行窗口,进入app.py所在的目录,并输入以下命令启动Flask应用程序:
```bash
python app.py
```
现在,您可以在浏览器中访问http://localhost:5000/,您应该能够看到一个包含聚类图的Leaflet地图。
阅读全文