vue-google-maps-loader
v2.2.2
Published
A Vue 3 composable for loading the Google Maps JavaScript API with reactive locale switching.
Maintainers
Readme
vue-google-maps-loader
A Vue 3 composable for loading the Google Maps JavaScript API with reactive locale switching.
✨ Features
- Built on the official @googlemaps/js-api-loader
- Vue 3 Composition API ready
- Works seamlessly with vue3-google-map via the
:api-promiseprop - Cleans up injected scripts, links, and styles
- Automatically reloads Maps API when the locale changes
🤔 Why use this?
The official @googlemaps/js-api-loader doesn't support:
- Locale switching - Can't reload the API with a different language at runtime
- Vue reactivity - No integration with Vue's reactive system
This composable solves these issues by wrapping the loader with Vue 3 reactivity and handling dynamic reloads.
🚀 Installation
npm install vue-google-maps-loader📖 API
useGoogleMapsLoader(apiOptions: APIOptions, locale: Ref<string>): {
isAvailable: Ref<boolean>;
apiPromise: Ref<Promise<typeof google>>;
}Parameters
apiOptions— Options passed to@googlemaps/js-api-loader(e.g.key,libraries,v). See the full list of options. Defaultslibrariesto['core']if not specified.locale— Any reactiveRef<string>with a BCP 47 language tag. The Maps API reloads automatically when this value changes.
Returns
isAvailable—falsebriefly during a locale reload (so dependent components unmount and remount with the new API),trueotherwise. AwaitapiPromisefor actual load completion.apiPromise— Resolves to thegoogleglobal once the API is loaded, or rejects if the script itself fails to load. Updates on each reload.
Call it once
useGoogleMapsLoader is a singleton. Only the first call initializes the loader — subsequent calls return the same instance regardless of the arguments passed. Call it once at the app or plugin level and use the returned refs anywhere in your app.
Handling load errors
apiPromise rejects only when the script never loaded at all: a network error, or a request blocked by a browser extension or by script-src.
Key problems do not reject. Google serves a working script for an invalid, unauthorized or unbilled key, so the promise resolves and isAvailable stays true. Those failures arrive later, as a console.error naming the cause (e.g. InvalidKeyMapError), a call to window.gm_authFailure if you define one, and an error overlay on the map. See Error messages.
⚡ Usage
With vue3-google-map
<script setup>
import { useI18n } from 'vue-i18n';
import { GoogleMap } from 'vue3-google-map';
import { useGoogleMapsLoader } from 'vue-google-maps-loader';
const { locale } = useI18n();
const apiOptions = { key: import.meta.env.VITE_GOOGLE_API_KEY };
const { isAvailable, apiPromise } = useGoogleMapsLoader(apiOptions, locale);
</script>
<template>
<GoogleMap
v-if="isAvailable"
:api-promise
:center="{ lat: 38.725282, lng: -9.149996 }"
:zoom="12"
style="width: 100%; height: 500px"
/>
</template>Standalone
<script setup>
import { useTemplateRef, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useGoogleMapsLoader } from 'vue-google-maps-loader';
const { locale } = useI18n();
const apiOptions = { key: import.meta.env.VITE_GOOGLE_API_KEY };
const { isAvailable, apiPromise } = useGoogleMapsLoader(apiOptions, locale);
const mapElement = useTemplateRef('map-element');
watch(
isAvailable,
async (available) => {
if (!available) return;
const google = await apiPromise.value;
new google.maps.Map(mapElement.value, {
center: { lat: 38.725282, lng: -9.149996 },
zoom: 12,
});
},
{ immediate: true },
);
</script>
<template>
<div
ref="map-element"
style="width: 100%; height: 500px"
/>
</template>locale can be any Ref<string> — this example uses vue-i18n, but any reactive ref works.
🧩 Compatibility
Server-side rendering
Browser-only. The composable reads document synchronously, so calling it during server-side rendering throws ReferenceError: document is not defined. Under Nuxt or a similar SSR setup, call it from client-only code — inside onMounted, or from a .client component.
Content Security Policy
Reloading assigns the Maps API script URL through a Trusted Types policy named vue-google-maps-loader. If your page enforces require-trusted-types-for 'script' and restricts policy names with a trusted-types directive, allow that name alongside the one @googlemaps/js-api-loader registers for the initial load:
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types @googlemaps/js-api-loader vue-google-maps-loaderPages that enforce Trusted Types without a trusted-types directive need no changes.
App styles that match Google's
Reloading removes <style> tags that appeared in document.head after the most recent load began and that mention Google's internal class names, such as gm-. A stylesheet of your own can match — hiding a control with .gm-style-cc { display: none } is the usual case — and is removed along with Google's.
Only untyped tags are considered: a <style> carrying a type attribute is skipped, as are tags already present when the load began and stylesheets loaded through a <link>. That covers most apps — Vite, for one, gives your own component styles a type in development. What stays exposed is an untyped <style> injected at runtime, from CSS-in-JS or from a dependency's styles routed through your bundler. Re-add it once the reload completes:
watch(isAvailable, (available) => {
if (available) injectMapStyles();
});⚠️ Disclaimer
Unofficial reload technique — Reloading the Maps API works by manually removing Google's injected scripts, stylesheets, and styles from the DOM and deleting
window.google.maps. This relies on internal implementation details that are not part of the Google Maps JavaScript API and are not guaranteed to remain stable across future updates.Incompatible with Google Maps Web Components — This loader cannot be used alongside Google Maps Web Components (e.g.
<gmp-map>), because custom elements cannot be unregistered once defined, making the reload strategy ineffective in those environments.
