Search code examples
javascriptgoogle-mapsgoogle-maps-api-3kmlgeoxml3

How to get bounds of a KMZ or KML file using geoxml3?


My project involves loading multiple kmz files from a directory containing about 600+ kmz/kml files. Max of 5 files will be loaded as user moves the map and clicks a button to load related kmz files. There will be a check to ensure that zoom is large enough so that the area covered isn't too broad.

To load relevant kmz/kml file, the idea is that if the placemarks from a kmz/kml fall even partially within the viewport then the file is loaded. To load these kmz/kml files quickly, I thought of the following steps:

Step 1: Extract the bounds of each kmz/kml file separately and store it in a file. I know how to get bounds of the viewport, map.getBounds(), and specific polygons in a kmz, geoXmlDoc.placemarks[i].polygon.bounds. But is there a way of getting bounds for the entire kmz file that includes all points, lines, polygons?

I understand this step needs to be done just once to generate the bounds file containing all kmz/kml files' bounds. I tried loading each file separately through a loop and calling getBounds of viewport but unfortunately the viewport does not exactly fit the kmz's bounds. The viewport is usually bigger.

Step 2: When user moves map to new location and clicks load relevant kmz files, then only the consolidated bounds array will be checked if the viewport bounds intersects with any of the kmz bounds.

if (currentBounds.intersects(all_bounds_array[i])) 
{
    // load the kmz file for index i
}

Solution

  • Create an empty LatLngBounds object. Ignore the map's current bounds.

    var bounds = new google.maps.LatLngBounds();
    

    Loop through all the contents of the KMZ file, extending that bounds with the various coordinates in your file

    bounds.extend(/* your coords */);