Displaying KML files from Google Drive on Leaflet maps throws bounds error

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?

maybe try a timeout before fitBounds, like 100ms. sometimes the kml isn’t fully loaded. also, check getBounds() to see if it gives valid coords b4 fitBounds. gl!

One thing that caught my attention in your code is that you’re calling getBounds() and fitBounds() immediately after adding the layer to the map. The L.KML plugin processes the data asynchronously, so even though you’ve parsed the XML, the actual geometry processing might not be complete yet. I’d suggest listening for the ‘ready’ event on the KML layer before attempting to get the bounds. Something like this should work better: javascript const kmlLayer = new L.KML(parsedKml); kmlLayer.on('ready', function() { myMap.fitBounds(kmlLayer.getBounds()); }); myMap.addLayer(kmlLayer); This ensures that the layer has finished processing all the geometries and calculating the bounds before you try to use them. I ran into this same timing issue when working with larger KML files that had multiple placemarks.

I’ve encountered this exact problem before when working with KML files from Google Drive. The main issue is that you’re using the wrong URL format to access the KML data. The Google Drive view URL doesn’t return the raw file content that your parser needs.

You need to convert your Google Drive sharing URL to the direct download format. Instead of using https://drive.google.com/file/d/YOUR_FILE_ID/view, change it to https://drive.google.com/uc?export=download&id=YOUR_FILE_ID. This will give you the actual KML content rather than the Drive preview page HTML.

Also worth checking if your KML file actually contains coordinate data - empty or malformed KML files will also trigger this bounds error since there’s nothing to calculate bounds from.