51 lines
1.2 KiB
TypeScript
51 lines
1.2 KiB
TypeScript
import { useEffect, useRef } from 'react';
|
|
import { useGoogleMap } from '@react-google-maps/api';
|
|
|
|
export function CustomAdvancedMarker({
|
|
position,
|
|
title,
|
|
iconUrl,
|
|
onClick
|
|
}: {
|
|
position: google.maps.LatLngLiteral;
|
|
title?: string;
|
|
iconUrl?: string;
|
|
onClick?: () => void;
|
|
}) {
|
|
const map = useGoogleMap();
|
|
const markerRef = useRef<any>(null);
|
|
|
|
useEffect(() => {
|
|
if (!map || !window.google?.maps?.marker?.AdvancedMarkerElement) return;
|
|
|
|
let content: HTMLElement | undefined;
|
|
if (iconUrl) {
|
|
const img = document.createElement('img');
|
|
img.src = iconUrl;
|
|
img.style.width = '32px';
|
|
img.style.height = '32px';
|
|
content = img;
|
|
}
|
|
|
|
markerRef.current = new window.google.maps.marker.AdvancedMarkerElement({
|
|
map,
|
|
position,
|
|
title,
|
|
content,
|
|
});
|
|
|
|
if (onClick && markerRef.current) {
|
|
markerRef.current.addListener('gmp-click', onClick);
|
|
}
|
|
|
|
return () => {
|
|
if (markerRef.current) {
|
|
google.maps.event.clearInstanceListeners(markerRef.current);
|
|
markerRef.current.map = null;
|
|
}
|
|
};
|
|
}, [map, position.lat, position.lng, title, iconUrl, onClick]);
|
|
|
|
return null;
|
|
}
|