Angular and Google Maps API: Integrating Maps

This tutorial will guide you through the process of integrating Google Maps API into an Angular project. We will cover everything from setting up a new Angular project to displaying a map on the page, adding markers and info windows, handling user interaction, and performing geocoding and reverse geocoding.

angular google maps api integrating maps

Introduction

Angular is a popular JavaScript framework for building web applications. It provides a robust set of tools and features that make it easy to develop scalable and maintainable applications. Google Maps API, on the other hand, is a powerful mapping platform that allows developers to add interactive maps and location-based services to their applications.

In this tutorial, we will combine the power of Angular with the versatility of Google Maps API to create a fully functional map application. We will demonstrate how to obtain an API key, load the Google Maps library, display a map on the page, add markers and info windows, handle user interaction, and perform geocoding and reverse geocoding.

Setting Up Angular

Before we can begin integrating Google Maps API into our Angular project, we need to set up a new Angular project and install the necessary dependencies.

Creating a new Angular project

To create a new Angular project, we can use the Angular CLI (Command Line Interface). Open a terminal or command prompt and run the following command:

ng new angular-maps-integration

This will create a new directory called angular-maps-integration with a basic Angular project structure.

Installing the necessary dependencies

Next, we need to install the necessary dependencies for integrating Google Maps API. Navigate to the project directory and run the following commands:

cd angular-maps-integration
npm install @agm/core

The @agm/core package is a wrapper around Google Maps API that provides Angular components and services for interacting with the map.

Integrating Google Maps API

Now that we have set up our Angular project and installed the necessary dependencies, we can proceed with integrating Google Maps API.

Obtaining an API key

To use Google Maps API, we need to obtain an API key. This key is required for authentication and tracking usage. To obtain an API key, follow these steps:

  1. Go to the Google Cloud Platform Console.
  2. Create a new project or select an existing project.
  3. Enable the Google Maps JavaScript API.
  4. Create an API key.
  5. Restrict the API key if desired (optional).

Make sure to keep your API key secure and do not share it publicly.

Loading the Google Maps library

To load the Google Maps library, we need to add it to our Angular project. Open the angular.json file in the root of your project and add the following code to the "scripts" section:

"scripts": [
  "https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
]

Replace YOUR_API_KEY with the API key you obtained in the previous step.

Displaying a map on the page

To display a map on the page, we will create a new Angular component called MapComponent. Run the following command to generate the component:

ng generate component map

This will create a new directory called map with the necessary files for our component.

Open the map.component.html file and add the following code:

<div class="map-container">
  <agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
    <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
  </agm-map>
</div>

In this code, we are using the agm-map and agm-marker components provided by the @agm/core package. We are also binding the latitude, longitude, and zoom properties to variables in our component.

Open the map.component.ts file and add the following code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent {
  lat = 51.5074;
  lng = -0.1278;
  zoom = 10;
}

In this code, we are setting the initial values for the latitude, longitude, and zoom properties.

To see the map in action, we need to add the MapComponent to the main AppComponent. Open the app.component.html file and replace the existing code with the following:

<app-map></app-map>

Run the following command to start the development server and open the application in your browser:

ng serve

You should now see a map displayed on the page with a marker at the specified coordinates.

Adding Markers and Info Windows

In this section, we will learn how to add markers to the map and display info windows when the markers are clicked.

Adding markers to the map

To add markers to the map, we can use the agm-marker component provided by the @agm/core package. Open the map.component.html file and modify the code as follows:

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
  <agm-marker [latitude]="lat" [longitude]="lng" [label]="'Marker'"></agm-marker>
  <agm-marker [latitude]="51.5074" [longitude]="-0.1278" [label]="'London'"></agm-marker>
  <agm-marker [latitude]="40.7128" [longitude]="-74.0060" [label]="'New York'"></agm-marker>
</agm-map>

In this code, we have added three markers to the map. Each marker is assigned a latitude and longitude value, and a label that will be displayed on the marker.

Customizing marker icons

By default, the markers on the map have a generic icon. We can customize the marker icons by providing a custom URL for the iconUrl property of the agm-marker component. Open the map.component.html file and modify the code as follows:

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
  <agm-marker [latitude]="lat" [longitude]="lng" [label]="'Marker'"></agm-marker>
  <agm-marker [latitude]="51.5074" [longitude]="-0.1278" [label]="'London'" [iconUrl]="'assets/marker.png'"></agm-marker>
  <agm-marker [latitude]="40.7128" [longitude]="-74.0060" [label]="'New York'" [iconUrl]="'assets/marker.png'"></agm-marker>
</agm-map>

In this code, we have added a marker.png file to the assets directory of our project and provided its URL as the iconUrl property of the markers.

Displaying info windows

To display info windows when the markers are clicked, we can use the agm-info-window component provided by the @agm/core package. Open the map.component.html file and modify the code as follows:

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
  <agm-marker [latitude]="lat" [longitude]="lng" [label]="'Marker'"></agm-marker>
  <agm-marker [latitude]="51.5074" [longitude]="-0.1278" [label]="'London'" [iconUrl]="'assets/marker.png'">
    <agm-info-window>
      <strong>London</strong>
      <p>The capital city of England.</p>
    </agm-info-window>
  </agm-marker>
  <agm-marker [latitude]="40.7128" [longitude]="-74.0060" [label]="'New York'" [iconUrl]="'assets/marker.png'">
    <agm-info-window>
      <strong>New York</strong>
      <p>The largest city in the United States.</p>
    </agm-info-window>
  </agm-marker>
</agm-map>

In this code, we have added an agm-info-window component as a child of each marker. Inside the info window, we have added a <strong> element for the title and a <p> element for the description.

Handling User Interaction

In this section, we will learn how to listen for map events and update the map based on user actions.

Listening for map events

To listen for map events, we can use the agm-map component's mapClick and mapReady output properties. Open the map.component.html file and modify the code as follows:

<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom" (mapClick)="onMapClick($event)" (mapReady)="onMapReady($event)">
  <!-- Markers and info windows code -->
</agm-map>

In this code, we have added the (mapClick) and (mapReady) event listeners to the agm-map component and bound them to methods in our component.

Open the map.component.ts file and add the following code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.css']
})
export class MapComponent {
  lat = 51.5074;
  lng = -0.1278;
  zoom = 10;

  onMapClick(event: any) {
    console.log(event);
  }

  onMapReady(event: any) {
    console.log('Map is ready');
  }
}

In this code, we have defined the onMapClick and onMapReady methods that will be called when the corresponding events occur. The onMapClick method logs the event object to the console, while the onMapReady method logs a simple message.

Updating the map based on user actions

To update the map based on user actions, we can modify the values of the latitude, longitude, and zoom properties in our component. Open the map.component.ts file and modify the onMapClick method as follows:

onMapClick(event: any) {
  this.lat = event.coords.lat;
  this.lng = event.coords.lng;
}

In this code, we are updating the latitude and longitude properties with the coordinates of the clicked location.

Geocoding and Reverse Geocoding

In this section, we will learn how to perform geocoding and reverse geocoding using Google Maps API.

Converting addresses to coordinates

To convert addresses to coordinates (geocoding), we can use the geocode method provided by the google.maps.Geocoder class. Open the map.component.ts file and modify the onMapClick method as follows:

onMapClick(event: any) {
  const geocoder = new google.maps.Geocoder();
  const latLng = new google.maps.LatLng(event.coords.lat, event.coords.lng);

  geocoder.geocode({ location: latLng }, (results, status) => {
    if (status === 'OK') {
      if (results[0]) {
        console.log(results[0].formatted_address);
      } else {
        console.log('No results found');
      }
    } else {
      console.log('Geocoder failed due to: ' + status);
    }
  });
}

In this code, we are creating a new instance of the google.maps.Geocoder class and passing the clicked coordinates to the geocode method. The geocode method takes a callback function that receives the results and status of the geocoding request. We are logging the formatted address of the first result to the console.

Converting coordinates to addresses

To convert coordinates to addresses (reverse geocoding), we can use the geocode method with the latLng property of the google.maps.Geocoder class. Open the map.component.ts file and modify the onMapReady method as follows:

onMapReady(event: any) {
  const geocoder = new google.maps.Geocoder();
  const latLng = new google.maps.LatLng(this.lat, this.lng);

  geocoder.geocode({ location: latLng }, (results, status) => {
    if (status === 'OK') {
      if (results[0]) {
        console.log(results[0].formatted_address);
      } else {
        console.log('No results found');
      }
    } else {
      console.log('Geocoder failed due to: ' + status);
    }
  });
}

In this code, we are using the latitude and longitude properties of our component to create a LatLng object. We are then passing this object to the geocode method to perform reverse geocoding.

Conclusion

In this tutorial, we have learned how to integrate Google Maps API into an Angular project. We have covered everything from setting up a new Angular project to displaying a map on the page, adding markers and info windows, handling user interaction, and performing geocoding and reverse geocoding.

By combining the power of Angular with the versatility of Google Maps API, you can create powerful and interactive map applications that provide location-based services to your users.

Feel free to explore the documentation of Google Maps API and the @agm/core package to discover more features and possibilities for your Angular map applications. Happy coding!