I’m using Next.js 14 with React Leaflet in a client component like so:
<>
<MapContainer
key={mapType}
center={location}
zoom={zoom}
className="rounded-l-2xl"
>
<CustomGoogleLayer
apiKey={process.env.NEXT_PUBLIC_MAPS_API_KEY}
type={mapType}
/>
</MapContainer>
</>
The CustomGoogleLayer uses @googlemaps/js-api-loader
and creates an instance of L.gridLayer.googleMutant
. However, occasionally, my guess is the script runs before googleMutant is loaded, resulting in the error: TypeError: L.gridLayer.googleMutant is not a function
It occurs around 20% of the time, more so on slower connections. I tested this in the chrome network tab by setting the throttle option to slow 4G or 3G. It looks like its a race condition, where the script tries to use L.gridLayer.googleMutant before its loaded.
Custom Google Layer code:
import * as React from 'react'
import * as L from 'leaflet'
import {
createLayerComponent,
updateGridLayer,
LeafletContextInterface,
LayerProps,
} from '@react-leaflet/core'
import 'leaflet.gridlayer.googlemutant/dist/Leaflet.GoogleMutant'
import { Loader, LoaderOptions } from '@googlemaps/js-api-loader'
interface IGoogleMapsAddLayer {
name: 'BicyclingLayer' | 'TrafficLayer' | 'TransitLayer'
options?: any
}
interface IProps extends L.gridLayer.GoogleMutantOptions {
zIndex?: number
useGoogMapsLoader?: boolean
googleMapsLoaderConf?: LoaderOptions
googleMapsAddLayers?: IGoogleMapsAddLayer[]
apiKey?: string
}
let googleMapsScriptLoaded = false
const createLeafletElement = (
props: IProps,
context: LeafletContextInterface
) => {
const {
apiKey = '',
useGoogMapsLoader = true,
googleMapsLoaderConf = {},
googleMapsAddLayers,
...googleMutantProps
} = props
if (useGoogMapsLoader && !googleMapsScriptLoaded) {
const loader = new Loader({ apiKey, ...googleMapsLoaderConf })
loader.load()
googleMapsScriptLoaded = true
}
const instance = L.gridLayer.googleMutant(googleMutantProps)
if (googleMapsAddLayers) {
googleMapsAddLayers.forEach((layer) => {
;(instance as L.gridLayer.GoogleMutant).addGoogleLayer(
layer.name,
layer.options
)
})
}
return { instance, context }
}
export default createLayerComponent<L.GridLayer, LayerProps & IProps>(
createLeafletElement,
updateGridLayer
)
I’m not sure how to fix this, but it results in a client side js error(TypeError: L.gridLayer.googleMutant is not a function
) sometimes and the map doesn’t load. After a few refreshes it fixes itself.
Unsure how to solve this and ensure that the googleMutant is added to gridLayer before the script runs, would appreciate any support!