The KmlLayer component renders KML or KMZ data on the map, allowing you to display geographic features from these file formats.
Import
import { KmlLayer } from '@react-google-maps/api';
Usage
import { GoogleMap, KmlLayer } from '@react-google-maps/api';
function MapWithKmlLayer() {
return (
<GoogleMap
center={{ lat: 41.876, lng: -87.624 }}
zoom={11}
>
<KmlLayer
url="https://example.com/data.kml"
options={{ preserveViewport: true }}
/>
</GoogleMap>
);
}
Props
The URL of the KML or KMZ file to display. The file must be publicly accessible.
options
google.maps.KmlLayerOptions
Options for configuring the KML layer.
The z-index of the layer.
onClick
(e: google.maps.MapMouseEvent) => void
Callback fired when a feature in the KML layer is clicked.Parameters:
e: The mouse event containing information about the clicked feature
Callback fired when the default viewport of the layer has changed. This occurs after the layer is loaded and the viewport is set to show all KML features.
Callback fired when the KML layer’s status changes. Use this to detect loading errors or successful loads.
onLoad
(kmlLayer: google.maps.KmlLayer) => void
Callback invoked when the KML layer instance has been created.Parameters:
kmlLayer: The KML layer instance
onUnmount
(kmlLayer: google.maps.KmlLayer) => void
Callback invoked when the component unmounts.Parameters:
kmlLayer: The KML layer instance
Example with Status Monitoring
import { useState } from 'react';
import { KmlLayer } from '@react-google-maps/api';
function MonitoredKmlLayer() {
const [status, setStatus] = useState<string>('loading');
const handleLoad = (kmlLayer: google.maps.KmlLayer) => {
console.log('KML layer loaded');
};
const handleStatusChanged = () => {
// Access the layer instance to check status
setStatus('Status changed');
};
return (
<KmlLayer
url="https://example.com/data.kml"
onLoad={handleLoad}
onStatusChanged={handleStatusChanged}
options={{
preserveViewport: false,
suppressInfoWindows: false,
}}
/>
);
}
Example with Click Handler
function InteractiveKmlLayer() {
const handleClick = (e: google.maps.MapMouseEvent) => {
console.log('KML feature clicked:', e.latLng?.toJSON());
};
return (
<KmlLayer
url="https://example.com/places.kml"
onClick={handleClick}
zIndex={1}
/>
);
}
TypeScript
import type { KmlLayerProps } from '@react-google-maps/api';
const kmlProps: KmlLayerProps = {
url: 'https://example.com/data.kml',
options: {
preserveViewport: true,
suppressInfoWindows: false,
},
zIndex: 1,
};