Tutorial

How To Integrate Google Maps in Angular with Angular Google Maps

Angular

Introduction

Google Maps is a map service provided by Google that supports a wide variety of configuration settings. Adding Google Maps to your application can provide users with more contextual information than a street address or set of coordinates.

Angular Google Maps are components that provide Angular applications with tools to utilize the Google Maps APIs.

In this tutorial, you will use the @agm/core library and create a map with a marker.

Prerequisites

To complete this tutorial, you will need:

Note: To avoid the “For development purposes only” messages when using the Google Maps API, you will need to provide a valid credit card and associate with a Billing account for the Google Cloud Project, but it is not required for this tutorial.

This tutorial was verified with Node v14.13.1, npm v6.14.8, angular v10.1.5, and @agm/core v1.1.0.

Step 1 — Setting Up the Project

You can use @angular/cli to create a new Angular Project.

In your terminal window, use the following command:

  • npx @angular/cli new angular-google-maps-example --style=css --routing=false --skip-tests

This will configure a new Angular project with styles set to “CSS” (as opposed to “Sass”, Less", or “Stylus”), no routing, and skipping tests.

Navigate to the newly created project directory:

  • cd angular-google-maps-example

From your project folder, run the following command to install @agm/core:

  • npm install @agm/core@1.1.0

Note: Presently there is a modern version 3.0.0-beta.0 release. If you opt to use this version, you should also install @types/googlemaps.

However, in the course of verifying this tutorial, we encountered issues that required using a downgraded version of @types/googlemaps (v3.39.12) and ultimately downgrading @agm/core (v1.1.0) to use the rectangle shape without errors.

Open app.module.ts in your code editor and modify it to support @agm/core:

src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AgmCoreModule } from '@agm/core';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgmCoreModule.forRoot({
      apiKey: 'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE'
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Be sure to replace 'YOUR_GOOGLE_MAPS_API_KEY_GOES_HERE' with your actual API key.

Warning: Be sure to avoid saving your API key in any files you commit to public repositories (like GitHub) as it can then be used by others for purposes you did not intend.

With the application ready to use @agm/core, you can create a custom component to use it.

Step 2 — Building an Example Map Component

Now, you can create the custom map component:

  • npx @angular/cli generate component MyAgmExample --flat=true --inlineStyle=true --inlineTemplate=true

This will create a new MyAgmExample component in the src/app directory without a separate CSS file or HTML template file. It will also add this new component to app.module.ts.

Open the new MyAgmExample.component.ts file and modify it to use agm-map:

src/app/MyAgmExample.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-agm-example',
  template: `
    <agm-map
      [latitude]="lat"
      [longitude]="lng"
      [mapTypeId]="mapType"
    >
    </agm-map>
  `,
  styles: [
    'agm-map { height: 300px; }'
  ]
})
export class MyAgmExampleComponent implements OnInit {
  lat = 21.3069;
  lng = -157.8583;
  mapType = 'satellite';

  constructor() { }

  ngOnInit(): void { }
}

This will create a new map with type satellite, latitude at 21.3069, and longitude at -157.8583 (Honolulu, Hawaii).

Note: You must explicitly set the height of the agm-map element in CSS.

Modify app.component.html to use this new my-agm-example component:

src/app/app.component.html
<my-agm-example></my-agm-example>

Then, start the application to observe what you have so far.

  • npm start

When visiting your application in a web browser, you should see a Google Map with a satellite view centered on Honolulu, Hawaii.

Step 3 — Building an Advanced Map Component with Markers and Bounds

Within the <agm-map> component’s template, you can add a number of other components. There are also some other configuration options you can set. This tutorial will only cover drawing shapes on your map, but it would be well worth checking out the full documentation on all of the options available to you.

Initializing the <agm-map> component with a latitude and longitude value will center the map at that particular coordinate. However, you may also place any number of markers and shapes at any location on your map.

Open the MyAgmExample.component.ts file and modify it to use agm-marker and agm-rectangle:

@Component({
  selector: 'my-agm-example',
  template: `
    <agm-map
      [latitude]="lat"
      [longitude]="lng"
      [zoom]="2"
      (mapClick)="addMarker($event.coords.lat, $event.coords.lng)"
    >
      <agm-marker
        *ngFor="let marker of markers"
        [latitude]="marker.lat"
        [longitude]="marker.lng"
        [opacity]="marker.alpha"
        [markerDraggable]="true"
        (markerClick)="selectMarker($event)"
      >
      </agm-marker>
      <agm-rectangle
        [north]="max('lat')"
        [east]="max('lng')"
        [south]="min('lat')"
        [west]="min('lng')"
      >
      </agm-rectangle>
    </agm-map>
    <p *ngIf="selectedMarker">
      Lat: {{ selectedMarker.lat }} Lng: {{ selectedMarker.lng }}
    </p>
  `,
  styles: [
    'agm-map { height: 300px; }'
  ],
})

export class MyAgmAdvancedExample {
  lat = 48.75606;
  lng = -118.859;

  selectedMarker = null;

  markers = [
    // These are all just random coordinates from https://www.random.org/geographic-coordinates/
    { lat: 22.33159, lng: 105.63233, alpha: 1 },
    { lat: 7.92658, lng: -12.05228, alpha: 1 },
    { lat: 48.75606, lng: -118.859, alpha: 1 },
    { lat: 5.19334, lng: -67.03352, alpha: 1 },
    { lat: 12.09407, lng: 26.31618, alpha: 1 },
    { lat: 47.92393, lng: 78.58339, alpha: 1 }
  ];

  addMarker(lat: number, lng: number) {
    this.markers.push({ lat, lng, alpha: 0.4 });
  }

  max(coordType: 'lat' | 'lng'): number {
    return Math.max(...this.markers.map(marker => marker[coordType]));
  }

  min(coordType: 'lat' | 'lng'): number {
    return Math.min(...this.markers.map(marker => marker[coordType]));
  }

  selectMarker(event) {
    this.selectedMarker = {
      lat: event.latitude,
      lng: event.longitude
    };
  }
}

First of all, you have set two additional properties on the map itself: an input to zoom and an event handler to mapClick. Zoom tells how far in or out to display the map initially; 0 is the farthest out to show, and depending on the location and type of map, it goes up to about 22. mapClick emits an event whenever a user clicks somewhere on the map. In this example, when a user clicks the map, it adds a new marker to the map.

Markers are like pins on the map. They have the following traits:

  • latitude and longitude are required
  • opacity which changes how transparent the marker looks
  • markerDraggable which allows the user to click, hold, and drag the marker around the map
  • markerClick which allows you to handle events when a user clicks on a single marker

In this tutorial, the markerClick will trigger addMarker which will drop a new pin with a different opacity.

The code has an array to hold all the markers for the map. And this array has been populated with a couple of random locations.

You have also added a rectangle shape to the map. The bounds of the rectangle - north, south, east, and west - are calculated by the farthest extremes of all the latitudes and longitudes of the markers. Based on this calculation, whenever a new marker is added, if it lies outside of the drawn rectangle, the rectangle will redraw to its new outer edge.

Also available is the AgmPolygon, AgmCircle, AgmPolyLine. Finally, the AgmDataLayer allows you to use GeoJSON to draw any of these features on the map.

Warning: Once you have concluded your experimentation, it is advised that you log in to your Google Cloud Console and remove the API key and remove the associated billing account to avoid potential misuse.

You now have a Google Map with markers and rectangle shapes.

Conclusion

In this tutorial, you learned how to use @agm/core and Google Maps API features in your Angular application.

This has great potential to show visitors locations for businesses, travel destinations, and points of interest.

If you’d like to learn more about Angular, check out our Angular topic page for exercises and programming projects.

Creative Commons License