Skip to content

Instantly share code, notes, and snippets.

@wlkns
Last active November 1, 2023 14:00
Show Gist options
  • Save wlkns/64d8ab123d9f2c3d4d8c6df61cb5ea9b to your computer and use it in GitHub Desktop.
Save wlkns/64d8ab123d9f2c3d4d8c6df61cb5ea9b to your computer and use it in GitHub Desktop.
Re-usable Google Maps loader (for Vite/Vue)
import { onMounted } from 'vue';
import loadMap from './load-google-map';
// In vite env make sure VITE_GOOGLE_MAPS_API_KEY= is defined.
onMounted(() => {
// Google maps API is not loaded at all
await loadMap();
// Google maps API is ready and loaded
});
// This can be used in as many Vue files as you need/want without any issues
// if the map is already loaded it will resolve as expected
var googleMapsInjected: boolean
var googleMapsApiLoaded: boolean
const callbacks: CallableFunction[] = []
function injectGoogleMapsScript() {
if (googleMapsInjected) return
const apiKey = import.meta.env.VITE_GOOGLE_MAPS_API_KEY as string
const script = window.document.createElement('script')
script.type = 'text/javascript'
script.src = `https://maps.googleapis.com/maps/api/js?key=${apiKey}&libraries=places&callback=googleMapsLoaded`
window.document.querySelector('head')?.appendChild(script)
googleMapsInjected = true
}
export default async function (): Promise<boolean> {
if (window.google?.maps?.version) {
googleMapsApiLoaded = true
}
if (googleMapsApiLoaded) {
return Promise.resolve(true)
}
window.googleMapsLoaded = function () {
googleMapsApiLoaded = true
callbacks.forEach((resolveFn) => resolveFn(true))
}
return new Promise(function (resolve) {
injectGoogleMapsScript()
callbacks.push(resolve)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment