Google Maps in Angular 20 with the JS API Loader

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.

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 loads config/environment.json (required) and, in dev mode, config/environment.local.json (optional). Put the .local.json in .gitignore so you can keep private keys out of source control.
  • Non-fatal dev overrides:
    If environment.local.json is missing, the catch returns an empty object so startup doesn’t fail.
  • Safe merging:
    Configs are shallow-merged, with a dedicated merge for googleMaps to avoid losing nested keys (apiKey, mapId, etc.).
  • DI tokens provided app-wide:
    APP_CONFIG exposes the full merged config;
    GOOGLE_MAP_INIT_CONFIG exposes 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 single mapId into mapIds: [mapId] and remove mapId from 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 get mapId and other loader options.
  • Uses Angular signals for options: options is a signal holding google.maps.MapOptions. If you ever update it (e.g., options.update(...)), the <google-map> input will react automatically.
  • Applies a styled map: Passing mapId ties the map to your Map Style from Google Cloud.
  • Sets initial view: center and zoom define the starting camera; colorScheme can 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.

Picture of Dmytro Litvinov

Dmytro Litvinov

Dmytro Litvinov, a seasoned Front-End Developer. He has been in that role for 9+ years, most of them as an Angular developer. Dmytro has experience in developing web applications and powerful business solutions in different domains: entertainment, trade union platforms, agricultural platforms, blockchain, and others. He knows how to build great software from scratch and has been a technical lead on several projects. His adaptability and domain knowledge have proven instrumental in ensuring the quality of software across varied industries.

Free Consultation

Sign up for a FREE consultation with one of Trailhead's experts.

"*" indicates required fields

This field is for validation purposes and should be left unchanged.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.