javascript - 如何在 Leaflet 中从 Google Drive 加载 KML?
问题描述
我正在尝试https://drive.google.com/file/d/1Ngi_nLWEYt-aCzX0dGioa8bP3K-UbUNP/view?usp=sharing
使用 Leaflet 在地图上显示 KML 文件(直接从 Google Drive 加载,例如)。使用下面的代码,这Error
会触发:
Uncaught (in promise) Error: Bounds are not valid. at i.fitBounds (leaflet.js:5) at index.html:45
怎么了?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"> </meta>
<title>Map</title>
<link rel = "stylesheet" href = "lib/leaflet.css"/>
<script src = "lib/leaflet.js"></script>
<script src = "lib/L.KML.js"></script>
<style type="text/css">
#pozadina{background-image: linear-gradient(to right,lightblue, rgb(36, 112, 226));}
#map{
height: 720px;
width: 86%;
padding-left: 7%;
padding-right: 7%;
}
#naslov{
color: rgb(15, 15, 199);
font-family: Verdana, Geneva, Tahoma, sans-serif;
text-align: center;
}
</style>
</head>
<body id="pozadina">
<h1 id="naslov">Map</h1>
<div id = "map"></div>
<script>
// Make basemap
const map = new L.Map('map', { center: new L.LatLng(44.786568, 20.448921), zoom: 11 });
const osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(osm);
// Load kml file
fetch("https://cors-anywhere.herokuapp.com/" +"https://drive.google.com/file/d/1Ngi_nLWEYt-aCzX0dGioa8bP3K-UbUNP/view?usp=sharing")
.then(res => res.text())
.then(kmltext => {
const parser = new DOMParser();
const kml = parser.parseFromString(kmltext, 'text/xml');
const track = new L.KML(kml);
map.addLayer(track);
console.log(track.getBounds());
map.fitBounds(track.getBounds()); //here is a problem
});
</script>
</body>
</html>
解决方案
您链接到的 KML 文件 ( https://drive.google.com/file/d/1Ngi_nLWEYt-aCzX0dGioa8bP3K-UbUNP/view?usp=sharing ) 位于 Google Drive 上,您指向的是 Share 链接。该共享链接会加载文件的 HTML 页面,并且不会下载文件本身。您需要一个直接下载实际 KML 文件的 URL。Google Drive 界面不提供这种类型的直接链接,但有一些说明会向您展示构建此类链接所需的 URL 模式。或者,您可以在其他一些服务上重新托管 KML 文件,该服务提供指向文件本身的简单直接链接。
推荐阅读
- python - python websockets,多个请求,为什么只收到请求?
- python - 在 python 中使用 scipy.integrate.quad 从速度方程计算位移
- python - 类数最多的通用对象识别
- r - 查找列中特定值的最大值?
- java - 如何在 GridBagLayout 中使中间列大于侧列?
- delphi - 如何在多设备应用程序中将 TGlyph 上显示的图像拉伸到 TGlyph 的大小?
- reactjs - 使用 graphql 客户端在组件之间传递获取状态
- kotlin - 使用 Detekt 的 Kotlin Var 到 Val?
- javascript - 在特定位置将安全号码更改为 X
- file - 从文件中读取一系列字节的最惯用方式