Angular 9|8|7 Add Google Maps with Location Search in Angular 2 plus Applications using Angular Google Maps Module (@agm/core) Easily

Google maps are used in many applications as a location with visible maps pays an important role to make information more user-friendly. Embedded Maps can display markers of location or enable visual selection of address or show geographical location reviews etc.

In this post, we will add Google Maps in an Angular project using the Angular Google Maps module. Adding/ Embedding Google Maps in an Angular project becomes very easy by using this module. Here we will explain step by step tutorial to make it even easier with a new sample Angular project using latest CLI current version 7.3.8

 

Let’s get mapped 😛

Check: Angular Google Maps with Radius Circle and Markers

 

Check working demo here

Create a new Angular project. You can update Angular CLI by running following npm command

$ npm install -g @angular/cli

$ ng new AngularGoogleMaps
$ cd AngularGoogleMaps

Install Angular Google Maps 

Run following NPM command to install AGM in project

$ npm install @agm/core --save

Next, open app.module.ts then import AgmCoreModule then add in imports array

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

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

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

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

Note: Replace apiKey with your API key. Check here on How to get Google API key?

Add the AGM template in the App component to show basic Google Map with the current location. To get current coordinates like Longitude & Lattitude, we will use geolocation service in the navigator.

<!-- app.component.html -->
<agm-map 
[latitude]="latitude" 
[longitude]="longitude" 
[zoom]="zoom" >
  <agm-marker 
  [latitude]="latitude" 
  [longitude]="longitude"></agm-marker>
</agm-map>

Here we will call setCurrentLocation() method to set AGM with Lattitude & Longitude.

[zoom] property can be used to zoom up to any level.

//app.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent  implements OnInit {
  title: string = 'AGM project';
  latitude: number;
  longitude: number;
  zoom:number;


  ngOnInit() {
    this.setCurrentLocation();
  }

    // Get Current Location Coordinates
    private setCurrentLocation() {
      if ('geolocation' in navigator) {
        navigator.geolocation.getCurrentPosition((position) => {
          this.latitude = position.coords.latitude;
          this.longitude = position.coords.longitude;
          this.zoom = 15;
        });
      }
    }

}

Add Map height in app.component.css

agm-map {
    height: 300px;
}

Note: Map height is required. Without it, the map will not be visible with 0 height.

That’s it now you have a basic Google Map working in Angular application. Next, we will add a search bar to search for locations from Google API. Then a Draggable Marker to get current location address.

Add Location/ Places Search bar

Next, we will install GoogleMaps types library

$ npm install @types/googlemaps --save-dev

Next, open file tsconfig.app.json already available at the root, now add “googlemaps” in types array as shown below

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": [
      "googlemaps"
    ]
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Make sure you have enabled three types of API’s services on your key.

Maps JavaScript API (Show Map), Places API (Places search results) & Geocoding API (Convert Lat & Long to address)

In app.component.html we will now add a search bar with address and Latitude & Longitude information.

The marker is now draggable so that user can drag it to the desired location.

[markerDraggable] option is set to true.

(dragEnd) the event will fire to get the address of current drop.
<!-- app.component.html -->
<div class="container">

  <h1>Angular Google Maps with Places Search Example</h1>

  <div class="form-group">
    <label>Enter address</label>
    <input type="text" class="form-control" (keydown.enter)="$event.preventDefault()" placeholder="Search Nearest Location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" #search>
  </div>

  <agm-map [latitude]="latitude" [longitude]="longitude" [zoom]="zoom">
    <agm-marker [latitude]="latitude" [longitude]="longitude" [markerDraggable]="true"
      (dragEnd)="markerDragEnd($event)"></agm-marker>
  </agm-map>

  <h5>Address: {{address}}</h5>
  <div>Latitude: {{latitude}}</div>
  <div>Longitude: {{longitude}}</div>
</div>

In app.component.ts we will add Google map Autocomplete method to return address data set. Geocoder location service will return address based on provided Latitude & Longitude in the method getAddress()

//app.component.ts

import { Component, OnInit, ViewChild, ElementRef, NgZone } from '@angular/core';
import { MapsAPILoader, MouseEvent } from '@agm/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title: string = 'AGM project';
  latitude: number;
  longitude: number;
  zoom: number;
  address: string;
  private geoCoder;

  @ViewChild('search')
  public searchElementRef: ElementRef;


  constructor(
    private mapsAPILoader: MapsAPILoader,
    private ngZone: NgZone
  ) { }


  ngOnInit() {
    //load Places Autocomplete
    this.mapsAPILoader.load().then(() => {
      this.setCurrentLocation();
      this.geoCoder = new google.maps.Geocoder;

      let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement);
      autocomplete.addListener("place_changed", () => {
        this.ngZone.run(() => {
          //get the place result
          let place: google.maps.places.PlaceResult = autocomplete.getPlace();

          //verify result
          if (place.geometry === undefined || place.geometry === null) {
            return;
          }

          //set latitude, longitude and zoom
          this.latitude = place.geometry.location.lat();
          this.longitude = place.geometry.location.lng();
          this.zoom = 12;
        });
      });
    });
  }

  // Get Current Location Coordinates
  private setCurrentLocation() {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition((position) => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude;
        this.zoom = 8;
        this.getAddress(this.latitude, this.longitude);
      });
    }
  }


  markerDragEnd($event: MouseEvent) {
    console.log($event);
    this.latitude = $event.coords.lat;
    this.longitude = $event.coords.lng;
    this.getAddress(this.latitude, this.longitude);
  }

  getAddress(latitude, longitude) {
    this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, status) => {
      console.log(results);
      console.log(status);
      if (status === 'OK') {
        if (results[0]) {
          this.zoom = 12;
          this.address = results[0].formatted_address;
        } else {
          window.alert('No results found');
        }
      } else {
        window.alert('Geocoder failed due to: ' + status);
      }

    });
  }

}

For making it look beautiful we have added bootstrap.css in index.html

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

 

Check working demo here

That’s it! Run application $ ng serve --open to see a Google Map with Search Bar to search places. The marker can be dragged anywhere to get location address with coordinates.

Subscribe
Notify of
45 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Is it possible to show a button to redirect me to my location after I change the address?

Honestly getting maps working has been so difficult for me to figure out for a very long time – this tutorial was amazing! Thank you so much for writing this up!!

It gives error at view child says two parameters are required given one

Why do I get this problem:
./node_modules/@agm/core/fesm5/agm-core.js 4538:120-128
“export ‘ɵɵinject’ was not found in ‘@angular/core’ ??

Diego Arredondo

Hi! Works pretty well. Is there any way we can force the suggestions to be relatively close to the location?

Search bar is also not working, can anyone help me