Angular Google Maps with Places Search Example

By Hardik Savani | October 31, 2020 | Category : Angular


Hi All,

Today, i will let you know example of angular google maps with places search example. you will learn angular google maps search address . step by step explain angular google maps search box example. let’s discuss about search place in google maps angular.

You can easily use google maps with places search in angular 6, laravel 7, angular 8, angular 9, angular 10 and angular 11 application.

Agm npm package provide google map api where you can easily use google maps. here i will give you step by step very simple example of how to integrate google maps in angular. we will install agm/core npm package and set current latitude and longitude with marker. so you have to just follow bellow step to create very basic example, you can also see bellow preview:

Preview:

Step 1: Create New App

You can easily create your angular app using bellow command:

ng new myNewApp

Step 2: Install agm/core npm Package

Now in this step, we need to just install agm/core in our angular application. so let's add as like bellow:

npm install @agm/core --save

we also need to install "@types/googlemaps" for google maps library. so let's run bellow command to install googlemaps npm.

npm install @types/googlemaps --save-dev

next, we need to open "tsconfig.app.json" from root folder and you need to add "googlemaps" in types array as like bellow i added:

tsconfig.app.json

{

"extends": "./tsconfig.base.json",

"compilerOptions": {

"outDir": "./out-tsc/app",

"types": [

"googlemaps"

]

},

"files": [

"src/main.ts",

"src/polyfills.ts"

],

"include": [

"src/**/*.d.ts"

]

}

Step 3: Import Material AgmCoreModule

Now, here we will import AgmCoreModule from @agm/core and then we add on declarations part. in this file we also need to add Google API Key need to add. you can generate google api key from here: Google Console. so let's update app.module.ts file as like bellow:

src/app/app.module.ts

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

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

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

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { FormsModule } from '@angular/forms';

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

@NgModule({

declarations: [

AppComponent

],

imports: [

BrowserModule,

BrowserAnimationsModule,

FormsModule,

AgmCoreModule.forRoot({

apiKey: 'GOOGLE API KEY',

libraries: ['places']

})

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

Step 4: Update Ts File

here, we need to update ts file as like bellow with lat and long variable:

src/app/app.component.ts

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

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

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

styleUrls: ['./app.component.css']

})

export class AppComponent {

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() {

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(() => {

let place: google.maps.places.PlaceResult = autocomplete.getPlace();

if (place.geometry === undefined || place.geometry === null) {

return;

}

this.latitude = place.geometry.location.lat();

this.longitude = place.geometry.location.lng();

this.zoom = 12;

});

});

});

}

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);

});

}

}

getAddress(latitude, longitude) {

this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, 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);

}

});

}

}

Step 5: Update HTML File

here, we need to update html file as like bellow code:

src/app/app.component.html

<div class="container">

<h1>Angular Google Map with Search Box Example - ItSolutionStuff.com</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"

></agm-marker>

</agm-map>

<h5>Address: {{address}}</h5>

<div>Latitude: {{latitude}}</div>

<div>Longitude: {{longitude}}</div>

</div>

Now you can run by bellow command:

ng serve

now you can check it.

I hope it can help you...




Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: