I have a Next.js
page which shows a Map component using the Advanced Markers functionality documented here. I'm intermittently getting the following error when the page loads:
InvalidValueError: initMap is not a function
If the user navigates away from the page and then returns, there's no error.
Because of the Advanced Markers functionality the script can't be imported as a package, so instead I'm using the Next.js
Script
tag. I use a useEffect to check that we have a window
, and I'm also using setInterval to delay running the initMap
code until (in theory) the script is loaded.
useEffect(() => {
function initMap() {
const interval = setInterval(() => {
if (
typeof window !== "undefined" &&
window.google &&
window.google.maps
) {
clearInterval(interval);
if (googlemap.current) {
const map = new google.maps.Map(googlemap.current, {
center: { lat: coords[0]?.lat, lng: coords[0]?.lng },
zoom: 15,
mapId: "d2a1a27e40cc216a",
});
const bounds = new google.maps.LatLngBounds();
for (const coord of coords) {
const advancedMarkerView =
new google.maps.marker.AdvancedMarkerView({
map,
content: buildContent(coord),
position: { lat: coord?.lat, lng: coord?.lng },
zIndex: 1,
});
const element = advancedMarkerView.element;
bounds.extend(advancedMarkerView.position);
}
map.fitBounds(bounds);
}
}
}, 1000);
}
initMap();
}, []);
return (
<>
<Script src='https://maps.googleapis.com/maps/api/js?key=API_KEY&v=beta&libraries=marker&callback=initMap' />
<div ref={googlemap} className='h-full w-full'></div>
</>
)
Can anyone see what I' doing wrong? What's the correct, rock-solid way of implementing a Google map in Next.js
using the Javascript API and Advanced Markers functionality, please?