问题描述
我是 JS 和 Leaflet 的新手,我正在尝试使用 Leaflet-Realtime 来显示本地 .txt 文件,但没有成功。
我知道我必须将我的 .TXT 文件转换为 GEOJSON 才能读取它。
文件格式:
- 没有标题。
- 只需要第 4 列和第 6 列
-1 06/10/2020 08:35:43 45.72125602 N 11.363634 E 198.2 M 4
-1 06/10/2020 08:35:44 45.721256 N 11.36363403 E 198.19 M 4
-1 06/10/2020 08:35:45 45.72125598 N 11.36363402 E 198.19 M 4
-1 06/10/2020 08:35:46 45.72125596 N 11.36363401 E 198.2 M 4
2 06/10/2020 08:35:50 45.72125595 N 11.3636341 E 198.2 M 4
目前我尝试的是在脚本中编写 GEOJSON 以便能够显示它,但它不起作用:
var map = L.map('map',{
minZoom: 1,maxZoom: 30,rotate: true
}).setView([45.64364529,10.20162995],17);
L.tileLayer('https://api.maptiler.com/maps/streets/{z}/{x}/{y}.png?key=H8dFchQ0uLgjRY4sSXUK',{
attribution: '<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a> <a href="https://www.openstreetmap.org/copyright" target="_blank">© OpenStreetMap contributors</a>'
}).addTo(map);
var latlngs = {
"geometry": {
"type": "polygon","coordinates": [
[ 45.64172279,10.19579398],[ 45.64193714,10.1958776],[ 45.64220345,10.19598908],[ 45.6423983,10.19606341],[ 45.6429504,10.19632354],[ 45.64329464,10.19658367],[ 45.64341805,10.19758703],[ 45.64339856,10.19838601],[ 45.64313876,10.1987855],[ 45.64244377,10.19869259],[ 45.6418527,10.19879479],[ 45.6415669,10.19715967],[ 45.64170331,10.19648147],[ 45.64189167,10.19615631]
]
},"type": "Feature","properties": {}
};
// Real Time
L.realtime({
latlngs,crossOrigin: true,type: 'json'
},{
interval: 60 * 1000,start: false
});
解决方法
对于寻找答案的未来用户:
我最终使用了 Leaflet 插件“Leaflet.Liveupdate”并且非常适合我。
L.control.liveupdate ({
update_map: function () {
...
},position: 'topleft'
})
.addTo(map)
.startUpdating();
将文件解析为数组:
getData();
async function getData() {
const response = await fetch('file.txt');
// console.log(response);
const data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row => {
const out = []
table.forEach(row => {
const colums = row.split('\t');
const lat = colums[3];
const lng = colums[5];
out.push([lat,lng]);
});
完整代码:
L.control.liveupdate({
update_map: function() {
getData();
async function getData() {
const response = await fetch('file.txt');
// console.log(response);
const data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row => {
const out = []
table.forEach(row => {
const colums = row.split('\t');
const lat = colums[3];
const lng = colums[5];
out.push([lat,lng]);
});
// console.log(out)
var latlng = [
out
];
var polyline = L.polyline(latlng,{
color: 'rgba(0,0)',// color: 'red',weight: 10
}).addTo(map);
})
}
},position: 'topleft',interval: 500 //10000 = 1 seg
})
.addTo(map)
.startUpdating().stopUpdating();
});