Integrating Google Maps in Your Angular Application

Seth Gwartney

If your Angular application calls for an interactive Google Map, manually adding the Maps API functionality is not quite as straightforward as you might think it should be. Luckily, we live in the world of Open Source, and because Angular has such an active developer community, some awesome people have already solved many of these problems and packaged it up nicely in an Angular module you can import into your application.

🐊 Alligator.io recommends

Our recommended Angular courses

Getting Started

First and foremost, in order to do any kind of interaction with the Maps API, you need an API key from Google. Follow the instructions here to get that set up.

Install and configure Angular Google Maps

From your project folder, run the following command:

$ npm i @agm/core --save

Now in app.module.ts:

import { AgmCoreModule } from '@agm/core';

@NgModule({
  imports: [
    ...,
    AgmCoreModule.forRoot({
      apiKey: 'YOUR GOOGLE MAPS API KEY'
      /* apiKey is required, unless you are a 
      premium customer, in which case you can 
      use clientId 
      */
    })
  ],
  ...
})
export class AppModule { }

Now in your templates you can include the map component. Note: you must explicitly set the height of the agm-map element in CSS.

In your component:

@Component({
  selector: 'your-comp',
  styles: ['agm-map { height: 300px; /* height is required */ }'],
  template: `
    <agm-map [latitude]='latitude' [longitude]='longitude' 
      [mapTypeId]='mapType'>
    </agm-map>
  `
})
export class YourComponent {
  latitude = -28.68352;
  longitude = -147.20785;
  mapType = 'satellite';
}

And there you have it! It really is that simple to get it set up. However, there are a host of other options and components that you can use to enrich the Google Maps experience.

Advanced Techniques

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. We’ll only cover drawing shapes on your map in this article, 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. Let’s try some of this in your component. I have created a StackBlitz for you to be able to see this all in action.

@Component({
  selector: 'hello',
  styles: ['agm-map { height: 300px; /* height is required */ }'],
  template: `
    <agm-map
      [latitude]="latitude"
      [longitude]="longitude"
      [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>
  `
})
export class HelloComponent {
  lat = 43.879078;
  lng = -103.4615581;
  selectedMarker;
  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
    };
  }
}

We’ve got a little more going on here. First of all, we’ve 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 - you guessed it - 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. I’ve created an array to hold all the markers for the map, and have hard-coded a few to begin with. latitude and longitude are required, but I’ve also added a few other optional properties: opacity which changes how transparent the marker looks; markerDraggable which allows the user to click, hold, and drag the marker around the map; and markerClick, which allows us to handle events when - you guessed it again - a user just clicks on a single marker, In this case, it’s just dropping a new pin wherever the click happens, but it’s giving all new pins a more transparent look.

We have also drawn a simple rectangle over the map. The bounds of the rectangle - north, south, east, and west - are calculated by the farthest extremes of all the markers’ latitudes and longitudes. Based on this calculation, whenever we click to add a new marker, if it lies outside of the drawn rectangle, the rectangle will redraw to it’s 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.

Further Reading

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#