Implement Google Maps in Angular 18
When developing an Angular application, integrating Google Maps can significantly enhance the user experience, especially for location-based services. This guide will walk you through the steps to implement Google Maps in an Angular 18 application using standalone components.
Step 1: Install Required Packages
To get started, you need to install the necessary packages for Google Maps integration in your Angular project. Open your terminal and run the following command:
npm install @angular/google-maps
Step 2: Include Google Maps API
Next, you need to include the Google Maps API in your index.html
file. Add the following script tag inside the <head>
section, replacing YOUR_API_KEY
with your actual Google Maps API key:
<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
Step 3: Create a Map Component
Create a new component for displaying the map. For instance, BranchesMapComponent
. This component will handle rendering the map and markers.
import { Component, ViewChild, signal, effect } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GoogleMapsModule, MapInfoWindow, MapMarker } from '@angular/google-maps';
import { RouterModule } from '@angular/router';
import { Branch, BranchMapMarker } from '../models';
@Component({
selector: 'app-branches-map',
standalone: true,
imports: [
CommonModule,
GoogleMapsModule,
RouterModule,
],
providers: [BranchService],
templateUrl: './branches-map.component.html',
styleUrls: ['./branches-map.component.scss'],
})
export class BranchesMapComponent {
@ViewChild(MapInfoWindow) infoWindow: MapInfoWindow | undefined;
branches = signal<Branch[]>([]);
center: google.maps.LatLngLiteral = { lat: 46.8182, lng: 8.2275 }; // Center of Switzerland
zoom = 8;
markers: BranchMapMarker[] = [];
selectedBranch = signal<Branch | null>(null);
constructor(private branchService: BranchService) {
effect(
() => {
// Assign markers to data
this.markers = this.getMarkers();
},
{ allowSignalWrites: true }
);
}
getMarkers() {
return this.branches()
.map((branch) => {
const marker: BranchMapMarker = {
label: '',
position: { lat: branch.lat, lng: branch.lng },
title: branch.name,
options: { animation: google.maps.Animation.DROP },
branch: branch,
};
return marker;
})
.filter(
(marker) => !isNaN(marker.position.lat) && !isNaN(marker.position.lng)
);
}
openInfoWindow(branch: Branch, marker: MapMarker): void {
this.selectedBranch.set(branch);
if (this.infoWindow) {
this.infoWindow.open(marker);
}
}
}
Create a new interface for the custom BranchMapMarker
to resolve the TypeScript errors:
export interface BranchMapMarker {
branch: Branch;
position: {
lat: number;
lng: number;
};
title: string;
options: {
animation: google.maps.Animation;
};
label: string;
click?: () => void;
}
Step 4: Define the HTML Template
Create an HTML template for the map component in branches-map.component.html
:
<google-map [center]="center" [zoom]="zoom" height="500px" width="100%">
<map-marker
*ngFor="let marker of markers"
#mapMarker="mapMarker"
[position]="marker.position"
[label]="marker.label"
[title]="marker.title"
[options]="marker.options"
(mapClick)="openInfoWindow(marker.branch, mapMarker)"
></map-marker>
<map-info-window>
// Define your HTML for the Map Markers
</map-info-window>
</google-map>
Step 5: Add Styles
Add any necessary styles for your component in branches-map.component.scss
:
/* Add your custom styles here */
Step 6: Fetch Data
An example of how your data could look like:
{ id: 1, name: 'Google', lat: 46.948, lng: 7.4474, postCode: '3000', canton: 'BE', location: 'Bern' }
Conclusion
By following these steps, you can successfully integrate Google Maps into your Angular 18 application using standalone components. This setup allows you to dynamically display and manage map markers based on your data, providing an interactive and informative map interface for your users. Remember to replace placeholders such as YOUR_API_KEY
and adapt the data fetching logic as per your application's requirements.
Resources:
https://github.com/angular/components/tree/main/src/google-maps#readme