In this guide, we’ll walk you through how to easily integrate Google Maps into your Angular 20 application using the Google Maps JavaScript API Loader. This method allows for dynamic loading of the Maps API, keeping your bundle size lean, enabling lazy loading, and preventing potential race conditions when the Maps library is not ready.
By the end of this tutorial, you’ll have a fully functional Google Maps integration in your Angular app with better control over versions, libraries, and error handling.
What is the Google Maps JavaScript API Loader?
The @googlemaps/js-api-loader package (installed via npm) lets you dynamically load the Google Maps JavaScript API in your app, rather than hard-coding a <script> tag in index.html. This keeps your bundle lean, enables lazy loading, and helps you avoid race conditions when the Maps library isn’t ready yet.
Why Use It?
- Lazy Loading: Load Maps only where needed to improve performance.
- Version & Library Control: Manage Google Maps versions and libraries (e.g., Places, Geometry, Marker) via TypeScript.
- Predictable Initialization: Ensures consistent initialization and error handling.
- Dynamic Configuration: Support different API keys and Map IDs per environment or client, enabling custom styling.
Official docs: Load the Maps JavaScript API with the JS API Loader.
About v2.0 of @googlemaps/js-api-loader
A recent 2.0 release introduced internal refactoring and some breaking changes. If you’re upgrading from 1.x, review the project’s migration guide to update your imports and options where needed.
- Migration guide: js-api-loader Migrations.
Prerequisites & Install
# Create new project via Angular CLI
ng new map-js-api-loader
# Optional Angular components for Maps
npm i @angular/google-maps
# Types for TS
npm i -D @types/google.maps
# Official JS API Loader
npm i @googlemaps/js-api-loader
Optional (rarely needed): if your tsconfig.app.json uses the types field, ensure it includes the Google Maps types:
{
"compilerOptions": {
"types": ["google.maps"]
}
}
Getting the API key & Map ID (official docs)
To get started, you need to generate an API key and, if necessary, a Map ID for custom map styles.
- API Key: Follow Google’s setup docs to generate an API key and enable the Maps JavaScript API. Make sure to restrict the API key for security.
- Map ID: If you want custom styling for your map, you can create a Map ID by following Google’s instructions here.
Runtime Config (environment.json)
I previously wrote about dynamic environment swapping in “Efficient Angular Environment Management with Azure Pipelines.”.
Create a runtime file (e.g., public/config/environment.json) that your app fetches at startup:
{
"googleMaps": {
"apiKey": "YOUR_API_KEY_HERE",
"mapId": "YOUR_MAPID_HERE",
"region": "US",
"language": "en"
}
}
You can add more fields (e.g., api.baseApiUrl, feature flags) and swap this file per env/client without rebuilding.
Strong Typing & DI Tokens
src/app/interfaces/app-config.interface.ts
export interface IAppConfig {
// Other configuration properties can be added here as needed
googleMaps: {
/**
* Google Maps API key obtained from Google Cloud Console.
* Used to authenticate requests to Maps services.
*/
apiKey: string;
/**
* Map ID for styling maps via the Maps Platform.
*/
mapId: string;
/**
* Optional region code (ISO 3166-1 alpha-2) to bias geocoding and map results.
* Example: 'US', 'GB'.
*/
region?: string;
/**
* Optional language code to localize map UI and results.
* Example: 'en', 'uk'.
*/
language?: string;
};
}
src/app/providers/app-config.token.ts
import { InjectionToken } from '@angular/core';
import { IAppConfig } from '../interfaces/app-config.interface';
export const APP_CONFIG = new InjectionToken<IAppConfig>('APP_CONFIG');
src/app/providers/google-map-init-config.token.ts
import { InjectionToken } from '@angular/core';
import { APIOptions } from '@googlemaps/js-api-loader';
/**
* Interface for Google Map Initialization Configuration.
* This interface is used to define the configuration options for initializing Google Maps.
*
* Available Libraries https://developers.google.com/maps/documentation/javascript/libraries#libraries-for-dynamic-library-import.
*/
export interface IGoogleMapInitConfig extends Omit<APIOptions, 'mapIds'> {
mapId: string;
}
/**
* InjectionToken for Google Map Initialization Configuration.
* This token is used to inject the configuration for initializing Google Maps into Angular's dependency injection system.
*/
export const GOOGLE_MAP_INIT_CONFIG: InjectionToken<IGoogleMapInitConfig> =
new InjectionToken<IGoogleMapInitConfig>('GOOGLE_MAP_INIT_CONFIG');
Load Config at Startup & Provide Tokens (main.ts)
src/main.ts
/**
* src/main.ts
*
* Application entry point.
*
* Responsibilities:
* - Load runtime configuration from `config/environment.json` and, when in dev mode,
* `config/environment.local.json`.
* - Merge environment and dev environment configs, with `devEnv` overriding `env`.
* - Initialize the Angular application by calling `bootstrapApplication`.
* - Provide application-wide tokens: `APP_CONFIG` and `GOOGLE_MAP_INIT_CONFIG`.
*
* Notes:
* - The runtime config shapes the behavior of the app (API endpoints, feature flags,
* and third-party keys such as Google Maps).
* - When `isDevMode()` is true, `environment.local.json` is attempted but failures
* fall back to an empty config to avoid blocking startup.
*/
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { App } from './app/app';
import { isDevMode } from '@angular/core';
import { IAppConfig } from './app/interfaces/app-config.interface';
import { APP_CONFIG } from './app/providers/app-config.token';
import { GOOGLE_MAP_INIT_CONFIG } from './app/providers/google-map-init-config.token';
/**
* Load base environment config and optional local overrides, then bootstrap the app.
*
* Implementation details:
* - `Promise.all` runs two operations in parallel:
* 1. Fetch the canonical `config/environment.json`.
* 2. If running in dev mode, attempt to fetch `config/environment.local.json`.
* If that fetch fails, an empty object typed as `IAppConfig` is used so the app
* can continue to start with just the base environment config.
* - The two configs are merged with shallow spreading. The `googleMaps` section
* is merged separately to ensure nested keys such as `apiKey` and `mapId` are
* correctly overridden by local dev values when present.
* - `APP_CONFIG` token is provided with the final merged config.
* - `GOOGLE_MAP_INIT_CONFIG` token is provided with the Google Maps init values,
* supplying sensible defaults for `region` and `language`.
*/
void Promise.all([
// Required runtime configuration shipped with the application
fetch('config/environment.json').then(response => response.json()),
// Optional local overrides used during development. Failure to load is non-fatal.
isDevMode()
? fetch(`config/environment.local.json`)
.then(response => response.json())
.catch(() => ({} as IAppConfig))
: Promise.resolve({} as IAppConfig),
])
// Merge base and dev configs; dev values override base values.
.then(([env, devEnv]: [IAppConfig, IAppConfig]) => ({
...env,
...devEnv,
// Merge nested googleMaps object so nested keys are preserved/overridden correctly.
googleMaps: {
...env.googleMaps,
...devEnv.googleMaps,
},
}))
.then((config: IAppConfig) => {
// Bootstrap Angular with the resolved configuration and providers.
bootstrapApplication(App, {
...appConfig,
providers: [
...appConfig.providers,
// Make the merged runtime config available via dependency injection.
{
provide: APP_CONFIG,
useValue: config,
},
// Provide the Google Maps initialization config expected by @angular/google-maps.
{
provide: GOOGLE_MAP_INIT_CONFIG,
useValue: {
key: config?.googleMaps?.apiKey,
mapId: config?.googleMaps?.mapId,
region: config?.googleMaps?.region ?? 'US',
language: config?.googleMaps.language ?? 'en',
libraries: [], // add your libraries here
},
},
],
}).catch(err => console.error(err));
});
Here’s What We’ve Done:
- Runtime config files:
The app loadsconfig/environment.json(required) and, in dev mode,config/environment.local.json(optional). Put the.local.jsonin.gitignoreso you can keep private keys out of source control. - Non-fatal dev overrides:
Ifenvironment.local.jsonis missing, thecatchreturns an empty object so startup doesn’t fail. - Safe merging:
Configs are shallow-merged, with a dedicated merge forgoogleMapsto avoid losing nested keys (apiKey,mapId, etc.). - DI tokens provided app-wide:
APP_CONFIGexposes the full merged config;GOOGLE_MAP_INIT_CONFIGexposes only the Google Maps init options.
Load Google Maps Script and Libraries
In this example, we’ll load the Google Maps script and libraries during app initialization.
src/app/app.config.ts
import {
ApplicationConfig, inject,
provideAppInitializer,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { GOOGLE_MAP_INIT_CONFIG } from './providers/google-map-init-config.token';
import { importLibrary, setOptions } from '@googlemaps/js-api-loader';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
provideRouter(routes),
provideAppInitializer(() => {
// Initialize Google Map configuration
const mapConfig = inject(GOOGLE_MAP_INIT_CONFIG);
const options = { ...mapConfig, mapIds: [].concat(mapConfig.mapId ?? []) };
delete options?.mapId;
setOptions(options);
// Import default libraries.
// After this call the google map script will be automatically added to the DOM in the head section.
importLibrary('maps');
})
]
};
What We’re Doing Inside provideAppInitializer:
- Read DI config: We
inject(GOOGLE_MAP_INIT_CONFIG)to get runtime options (apiKey,mapId,region,language,libraries). - Normalize options: The loader expects
mapIds(array). We convert a singlemapIdintomapIds: [mapId]and removemapIdfrom the options object. - Configure the loader globally:
setOptions(options)applies these settings once for the entire app. - Kick off script loading:
importLibrary('maps')triggers injection of the Maps JS<script>into the document and begins loading the core maps library so subsequent imports (e.g.,places,marker) are faster and consistent.
You can later load additional libraries where needed:
await importLibrary('places'); // before using Autocomplete
await importLibrary('marker'); // for advanced marker features
Angular Google Maps Initialization
Here we initialize a Google Map in an Angular (standalone) root component using the config provided via DI.
src/app/app.ts
import { Component, inject, signal } from '@angular/core';
import { GoogleMap } from '@angular/google-maps';
import { GOOGLE_MAP_INIT_CONFIG } from './providers/google-map-init-config.token';
@Component({
selector: 'app-root',
imports: [GoogleMap],
templateUrl: './app.html',
styleUrl: './app.scss'
})
export class App {
readonly mapConfig = inject(GOOGLE_MAP_INIT_CONFIG);
options = signal<google.maps.MapOptions>({
mapId: this.mapConfig.mapId,
center: { lat: 24, lng: 12 },
zoom: 4,
colorScheme: 'LIGHT' // Can be LIGHT, DARK, or FOLLOW_SYSTEM
});
}
src/app/app.html
<google-map
height="400px"
width="750px"
[options]="options()"
/>
What This Example Does
- Injects runtime map config: We read
GOOGLE_MAP_INIT_CONFIG(provided at bootstrap) to getmapIdand other loader options. - Uses Angular signals for options:
optionsis a signal holdinggoogle.maps.MapOptions. If you ever update it (e.g.,options.update(...)), the<google-map>input will react automatically. - Applies a styled map: Passing
mapIdties the map to your Map Style from Google Cloud. - Sets initial view:
centerandzoomdefine the starting camera;colorSchemecan hint light/dark basemap on vector maps.
Result
To build and run your Angular application locally during development, you can use the Angular CLI’s ng serve command. It will starts a development server (usually on http://localhost:4200).
ng serve
Here’s the final result, see the video demo below.
What we saw:
- Confirmed that the Google Maps script was injected into the
<head>. - Verified a working Google Map rendering in the app.
- Demonstrated both Light and Dark map themes (via
mapId/colorScheme).
Conclusions
Using dynamic apiKey and mapId for Google Maps in Angular is straightforward and maintainable. By loading the Maps script with the official Loader (setOptions + importLibrary), keeping settings in a runtime JSON, and exposing them via DI tokens (APP_CONFIG, GOOGLE_MAP_INIT_CONFIG), you get clean initialization, safer key handling, and easy per-client styling. This pattern scales well for multi-tenant apps—swap keys and styles without a rebuild—while keeping your components simple and type-safe.
By following this approach to dynamically load Google Maps in your Angular 20 application, you’ll ensure better performance, cleaner configuration, and more flexible styling options. This method scales well for multi-tenant apps and provides an easy way to manage API keys and Map IDs.
Need help integrating maps into your web applications? Contact the experts at Trailhead to guide you every step of the way.


