How to Zoom to a KMZ Layer Using maplibre-gl-kmz-layer

It took me a while to figure out to zoom to a KMZ Layer using maplibre-gl-kmz-layer using MapLibre GL and the Gemini AI wasn’t exactly helpful. It’s quite simple if you use the getData() function your KMZ Layer, then pass the features object along to turf.bbox() to get the bounding box.

map.fitBounds(turf.bbox(kmzLayer.getData().features));

Here is a complete code example, that can be copied and pasted in your browser. You may have to change the KMZ file path, as my server does not allow hot linking, but other then that it will run locally.

<!DOCTYPE html>
<html lang="en">
<head>
	
    <link rel='stylesheet' href='https://unpkg.com/[email protected]/dist/maplibre-gl.css' />
    <script src='https://unpkg.com/[email protected]/dist/maplibre-gl.js'></script>
    <script src="https://cdn.jsdelivr.net/gh/northprint/maplibre-gl-kmz-layer@main/dist/maplibre-gl-kmz-layer.js"></script>
    
    <!-- required for finding the bbox of the underlying KMZ layer -->
    <script src="https://cdn.jsdelivr.net/npm/@turf/turf@7/turf.min.js"></script>
    
    <style>
        body { margin: 0; padding: 0; }
        html, body, #map { height: 100%; }
    </style>
</head>
<body>
<div id="map"></div>

<script>
	
// initial map set up with openfreemap
const map = new maplibregl.Map({
    container: 'map',
    zoom: 10,
    center: [ -74.62274, 43.68907],
    pitch: 0,
    bearing: 0,
    maxPitch: 95
});

map.setStyle('https://tiles.openfreemap.org/styles/bright');

// once the map is then fully load the KMZ layer
// so that it appears above all other layers

map.on('load', async () => {	  
	let kmzLayer = new MaplibreGLKMZLayer.KMZLayer({
	  id: 'kmz-layer',
	  url: 'https://andyarthur.org/data/kml_20266.kmz'
	});

  await kmzLayer.addTo(map);

  // to zoom to the KMZ layer, you need to get the underlying feature data
  // use the turf library to get the bounding box (bbox) and pass this along to
  // map.fitBounds

	map.fitBounds(turf.bbox(kmzLayer.getData().features));
});

</script>
</body>
</html>

OpenStreetMap: One of the World's Largest Collaborative Geospatial Projects - GIS Lounge
SVGZ Graphic: Cattle in America (2017)
SVGZ Graphic: Final USGS DRG Topographic Map Update
SVGZ Graphic: How Big is Texas?
SVGZ Graphic: Nearest Foreign Country
SVGZ Graphic: Percentage of Town Area Sloping North
SVGZ Graphic: Which is Closer - New York or Texas?
Terrain Map: Digital Terrain Models
Thematic Map: Big Foot Sightings

Leave a Reply

Your email address will not be published. Required fields are marked *