I’m working on a web mapping project where I need to show KML data stored on Google Drive using Leaflet. When I try to load the KML file and fit the map bounds to show all the data, I keep getting this error message:
Uncaught (in promise) Error: Bounds are not valid.
at i.fitBounds (leaflet.js:5)
at index.html:45
Here’s my current implementation:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>KML Viewer</title>
<link rel="stylesheet" href="leaflet/leaflet.css"/>
<script src="leaflet/leaflet.js"></script>
<script src="plugins/L.KML.js"></script>
<style>
body { background: linear-gradient(45deg, #e3f2fd, #1976d2); }
#mapContainer {
height: 600px;
width: 90%;
margin: 0 auto;
}
h2 { color: #0d47a1; font-family: Arial; text-align: center; }
</style>
</head>
<body>
<h2>KML Data Viewer</h2>
<div id="mapContainer"></div>
<script>
// Initialize map
const myMap = L.map('mapContainer').setView([45.2671, 19.8335], 10);
const tileLayer = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
myMap.addLayer(tileLayer);
// Fetch KML data
fetch("https://cors-anywhere.herokuapp.com/https://drive.google.com/file/d/YOUR_FILE_ID/view")
.then(response => response.text())
.then(kmlData => {
const xmlParser = new DOMParser();
const parsedKml = xmlParser.parseFromString(kmlData, 'text/xml');
const kmlLayer = new L.KML(parsedKml);
myMap.addLayer(kmlLayer);
console.log(kmlLayer.getBounds());
myMap.fitBounds(kmlLayer.getBounds()); // Error occurs here
});
</script>
</body>
</html>
The bounds seem to be undefined or invalid when I try to use fitBounds. What could be causing this issue and how can I fix it?