How to Get the User’s Current Location and Display It on a Map in Angular

Modern web applications often need to access the user’s location to provide personalized experiences — such as showing nearby stores, delivery tracking, or location-based services.

In this article, you’ll learn how to get the user’s current location in Angular and display it on an interactive Google Map. We’ll go step by step — from enabling the browser’s Geolocation API to rendering a map centered on the current coordinates.


Prerequisites

Before we begin, make sure you have the following:

  • An Angular project created with Angular CLI (ng new my-map-app)
  • A Google Maps API key
  • Basic understanding of TypeScript and Angular components

You can obtain a free API key from the Google Cloud Console.


Step 1: Add the Google Maps Script

In your index.html file, include the Google Maps JavaScript API by adding this script inside the <head> tag:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

⚠️ Replace YOUR_API_KEY with your real API key.
You can restrict it to your domain for security purposes.


Step 2: Create the Map Component

Next, create a dedicated Angular component that will handle both location retrieval and map rendering.

Run this command in your terminal:

ng generate component map-component

This will create a folder src/app/map-component with the necessary files.


Step 3: Install Google Maps Type Definitions

TypeScript needs to know about Google’s global google object. Install the type definitions:

npm install --save @types/googlemaps

Then, at the top of your map-component.component.ts, add:

/// <reference types="@types/googlemaps" />

Step 4: Implement the Component Logic

Open map-component.component.ts and replace its content with the following:

/// <reference types="@types/googlemaps" />
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-map-component',
  template: `<div #mapContainer class="map-container"></div>`,
  styles: [`
    .map-container {
      height: 400px;
      width: 100%;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
  `]
})
export class MapComponentComponent implements OnInit {
  @ViewChild('mapContainer', { static: false }) mapContainer!: ElementRef;

  ngOnInit(): void {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        position => this.showMap(position),
        error => this.handleError(error)
      );
    } else {
      alert('Geolocation is not supported by this browser.');
    }
  }

  private showMap(position: GeolocationPosition): void {
    const { latitude, longitude } = position.coords;
    const location = new google.maps.LatLng(latitude, longitude);

    const options: google.maps.MapOptions = {
      center: location,
      zoom: 14,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    const map = new google.maps.Map(this.mapContainer.nativeElement, options);
    new google.maps.Marker({
      position: location,
      map,
      title: 'You are here'
    });
  }

  private handleError(error: GeolocationPositionError): void {
    switch (error.code) {
      case error.PERMISSION_DENIED:
        alert('User denied the request for Geolocation.');
        break;
      case error.POSITION_UNAVAILABLE:
        alert('Location information is unavailable.');
        break;
      case error.TIMEOUT:
        alert('The request to get user location timed out.');
        break;
      default:
        alert('An unknown error occurred.');
        break;
    }
  }
}

Step 5: Register the Component in the App Module

Ensure that your component is declared in app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { MapComponentComponent } from './map-component/map-component.component';

@NgModule({
  declarations: [
    AppComponent,
    MapComponentComponent
  ],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 6: Display the Map in Your App

Open app.component.html and use the component selector:

<h2>Your Current Location</h2>
<app-map-component></app-map-component>

Now run your app:

ng serve

Then open http://localhost:4200 in your browser.
You’ll be prompted to allow location access — once you grant permission, the map will appear centered on your current coordinates, with a marker showing your location.


Common Errors and How to Fix Them

ErrorCauseSolution
“Cannot find name ‘google’”TypeScript doesn’t recognize Google Maps objectsRun npm install --save @types/googlemaps and add /// <reference types="@types/googlemaps" />
“app-map-component is not a known component”Component not declared or imported properlyAdd it to declarations in your app.module.ts
Blank map areaAPI not loaded or wrong keyCheck your API key and ensure the script tag loads before your component

Conclusion

By following these steps, you’ve learned how to:

  • Get the user’s current location using the HTML5 Geolocation API.
  • Display an interactive Google Map centered on that location.
  • Handle potential errors gracefully.

This simple integration can enhance user engagement in your Angular app by providing personalized, location-based experiences.

Whether you’re building a delivery tracker, travel guide, or local search app, adding maps and location awareness is a valuable feature for your users.

This article is inspired by real-world challenges we tackle in our projects. If you're looking for expert solutions or need a team to bring your idea to life,

Let's talk!

    Please fill your details, and we will contact you back

      Please fill your details, and we will contact you back