How To Use Google Maps In Your Angular Application? | Devstringx

Back to Blog
Google Maps In Your Angular Application

How To Use Google Maps In Your Angular Application? | Devstringx

Implementing google maps in your angular application may be interesting in the event that you don’t realize an accurate stream however following these straightforward strides for executing maps anybody can implement it easily

Create A New Angular Project

ng new google-maps

Run Project:-

ng serve -o

Install Angular Google Maps

To use google maps in your angular application, install @agm/core package

Run The Following Command To Install AGM Package

npm install @agm/core -save

Install Types For Google Maps

Next, we will install the GoogleMaps types library

npm install @types/GoogleMaps -save-dev

Next, open the tsconfig.app.json already available in the root, now add “GoogleMaps” in the types array as shown-

{

“extends”: “../tsconfig.json”,

“compilerOptions”: {

“outDir”: “../out-tsc/app”,

“types”: [

“googlemaps”

]

},

“exclude”: [

“test.ts”,

“**/*.spec.ts”

]

}

Update The App Module

Next, open the app.module.ts file, import AgmCoreModule then update the 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: ‘YOUR-API-KEY-HERE’,

libraries: [‘places’]

})

],

providers: [],

bootstrap: [AppComponent]

})
Export Class AppModule { }

During the import of AgmCoreModule, we need to define our Google Console API key under the API key property. Also, you have to enable the ‘places’ library to make a search for places.

Getting Google API Key

Go to the google console. You need to signup/sign up with your Google credentials.

https://console.developers.google.com/

On going to the above link you could get the Google API key for all the steps mentioned on this site.

Adding Google Maps To Component

For creating google maps in the template, we need to add <agm-maps/> component with binding properties for setting latitude, longitude, zoom, etc.

The map will also have a marker, which is created by adding <agm-marker/> component

<!- app.component.html ->

<agm-map

[latitude]=”latitude”

[longitude]=”longitude”

[zoom]=”zoom” >

<agm-marker

[latitude]=”latitude”

[longitude]=”longitude”>

</agm-marker>

</agm-map>

Add this to your template to show the basic map in your application

Add map height in app.component.css

AGM–map

{

height: 300px;

}

Updating The Component Class

Geocoder location service will return the address based on provided latitude, and longitude in the method getAddress()

The template reference variable #search on the input field is used to find the key events for fetching addresses based on the current location

The markerDragEnd() after the user stops marker drag to fetch the address of the current location

<!- 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>
Read Also:- CLI Angular Project Setup
//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);

}

});

}

}

FAQS

  • Does Google Maps use angular?

The second official @angular/component, a Google Maps angular map list, is introduced in the brand-new Angular Component pearl-lullaby (v9. 0.0-RC. 0).

  • How do I use Google Maps in angular 13?

New Angular project creation:

Here you can create an angular google map API key.

Go to the index.html file in your angular google maps example and add the next line inside your head tags:

  • You should add a google map to angular and your API Key inside the script tag.
  • Allowing Angular to access Google Maps types requires adding a type.
  • Does Google Maps use angular programming?

Angular An AngularJS application can use the google maps component angular using a collection of directives (part of angular-UI) written in Javascript and CoffeeScript.

  • What do Angular maps do?

The map() transformation operator in RxJS use to change each of the items that an Observable emits by applying a different function to it. Each value emitted by the source Observable is subjected to a specified angular 14 google maps function and the generated values are subsequently emitted as an Observable.

—————————————————————————————————————————————————-

Our Developers have written some other detailed articles on Angular Development you might find of interest:-

Share this post

Back to Blog