Google maps places autocomplete using Angular 2
Hello all,
Entering location manually could be the most annoying part any user can experience while using your application.
Maps Places autocomplete feature could be added to any particular application written in any specific language. Here we will do it using angular 2.
Angular or Angular 2/4 the latest buzz in the Javascript world is considered the best amongst many Javascript frameworks.
Before we proceed we need an angular project which we will create using angular cli.
Angular CLI
You all can refer to this Angular CLI.
- npm install @angular/cli -g
- ng new my-app
- cd my-app
- ng serve
note: MAC users should use npm install with administrative permissions (use sudo before command).
Now we need a package for using google maps components to achieve what we started on.
Angular Google Maps(AGM)
Angular Google Maps(AGM) contains serveral components to use google maps and its several components into your applications.
We use it by installing packages to our angular project.
- Install agm/core package:
npm install @agm/core --save-dev
- Install types/googlemaps package:
npm install @types/googlemaps --save-dev
Now since we are done with the setting up project for angular 2, Lets get into the actual coding part of it which is even more simple than this.
In your app.module.ts file add an import for AgmCoreModule.
import { AgmCoreModule } from '@agm/core';
now we need to import this in imports section
imports: [
AgmCoreModule.forRoot({
apiKey: 'your api key from google developers console',
libraries: ["places"]
})
]
In your app.component.html file add this code snippet:
<div class="container">
<h1>Google Maps Places Autocomplete Using Angular 2</h1>
<div class="form-group">
<input type="text" placeholder="Search for Location" autocorrect="off" autocapitalize="off" spellcheck="off" class="form-control" #search>
</div>
</div>
In this code we have used #search as a local variable which is of type ElementRef which will contain the whole input tag it placed in. We can access the value of this input text box using search.value.
For styling I have added bootstrap in this project.
Now coming on to the main logic for autocomplete feature. In your app.component.ts file add import for MapsAPILoader.
import { MapsAPILoader } from '@agm/core';
import {} from '@types/googlemaps';
import { ViewChild, ElementRef, NgZone } from '@angular/core';
Now inside the class AppComponent add this code:
@ViewChild('search') public searchElement: ElementRef;
constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}
ngOnInit() {
this.mapsAPILoader.load().then(
() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, { types:["address"] });
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
if(place.geometry === undefined || place.geometry === null ){
return;
}
});
});
}
);
}
Now lets understand what we did in the above code.
First we declared a public variable searchElement of type ElementRef and we referred it to the local variable search used in our HTML file using ViewChild.
After that we added a Listener on our autocomplete variable which loads the google maps places as you write text in the input box.
Final Output will look like this:
And for people who like to do it by watching video can watch the following video for reference.
Implementation
In your app.module.ts file add an import for AgmCoreModule.
import { AgmCoreModule } from '@agm/core';
now we need to import this in imports section
imports: [
AgmCoreModule.forRoot({
apiKey: 'your api key from google developers console',
libraries: ["places"]
})
]
In your app.component.html file add this code snippet:
<div class="container">
<h1>Google Maps Places Autocomplete Using Angular 2</h1>
<div class="form-group">
<input type="text" placeholder="Search for Location" autocorrect="off" autocapitalize="off" spellcheck="off" class="form-control" #search>
</div>
</div>
In this code we have used #search as a local variable which is of type ElementRef which will contain the whole input tag it placed in. We can access the value of this input text box using search.value.
For styling I have added bootstrap in this project.
Now coming on to the main logic for autocomplete feature. In your app.component.ts file add import for MapsAPILoader.
import { MapsAPILoader } from '@agm/core';
import {} from '@types/googlemaps';
import { ViewChild, ElementRef, NgZone } from '@angular/core';
Now inside the class AppComponent add this code:
@ViewChild('search') public searchElement: ElementRef;
constructor(private mapsAPILoader: MapsAPILoader, private ngZone: NgZone) {}
ngOnInit() {
this.mapsAPILoader.load().then(
() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, { types:["address"] });
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
if(place.geometry === undefined || place.geometry === null ){
return;
}
});
});
}
);
}
Now lets understand what we did in the above code.
First we declared a public variable searchElement of type ElementRef and we referred it to the local variable search used in our HTML file using ViewChild.
After that we added a Listener on our autocomplete variable which loads the google maps places as you write text in the input box.
Final Output will look like this:
And for people who like to do it by watching video can watch the following video for reference.
Thank You for posting this stuff.
ReplyDeleteIt is very helpful . Also the video is well structured.
Keep up the good work. Waiting for more stuff from your side.
Thank You
Deleteplease upload it on github and publish the link
DeleteI am having this problem
ReplyDeletehttp://imgur.com/a/yy7Di
got the error....my api key was not valid
DeleteGood!!
DeleteDo Comment If You Face any issue.
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined
ReplyDeleteHi Victor,
DeleteMake sure you have this import:
import {} from '@types/googlemaps';
and do comment if you face any issue further.
ReplyDeleteAbhishek can you suggest any book or site from where I can learn angular 2.
Hi,
DeleteFor learning I would suggest you to check the official angular docs but if you like to read books then go for ng-book 2 (very detailed explanation is there).
And also try to create applications as you read.
Thanks and do comment if you need any further help.
Thanks and do keep posting new videos
DeleteFor the above code I got this error :
Property 'auto complete' does not exist on type 'typeof places'
Make sure you have this import:
Deleteimport {} from '@types/googlemaps';
and do comment if you face any issue further.
also 'A' of autocomplete is in caps
DeleteStill not working
Deletehttps://drive.google.com/open?id=0BzBD-JCZBacJbnJGajNhX0R1UEk
it showing error here:: import { } from '@types/googlemaps'; that index.d.ts is not a module. can you please help
DeleteHow I can get data(token ) from third party login window and save it using angular js 2
ReplyDeleteOr
How I can control third party window through script
Do you know how to gain access to native Google Maps object by getNativeMap() from GoogleMapsAPIWrapper. My example from https://github.com/lzur/google-maps-example doesn't works.
ReplyDeletehello there!
ReplyDeletei followed all of your instructions (very helpful, by the way) but in my app, i have the search box in a side menu custom component, and while it does not throw any errors, the auto complete does not occur either
is there something else i must do to get the autocomplete to work in a custom component that is contained within the app.html? i have imported AGM to my components.module.ts and that has not helped either.
any insight would be much appreciated
thanks for all your time and effort!
i figured it out!
Deleteyou have to bind the search variable via document.body.getElementsByTagName('input')[0]
what a run-around! thanks again for the tutorials!
How can I get the latitude and longitude of the address searched?
ReplyDeleteJSON.stringify(place.geometry.location);
Deleteplease can u send full code to get the latitude and longitude of the address searched.
DeleteThis comment has been removed by the author.
DeleteHi thanks for tutorial but i have in console warning:
ReplyDeleteYou have included the Google Maps API multiple times on this page. This may cause unexpected errors. js:99:295
TypeError: a is undefined[Learn More]
How to fix this error? Thanks!
I have this error:
ReplyDeleteUncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
I think the problem is because my form this opens in a modal with templateref :/
DeleteHello Thanks very much for that tuto. (it help me also to use the DistanceMatrixService)
ReplyDeleteStill work fine, just i wodering to know why do you use Zone in this case.
I mean, i know (a little bit wath zone is) but including autocomplete in a zone.run, is it an enhance for the async call even if autocomplete.getPlace() is already in a listener ( called in the async stack in browser) ?
sorry for my bad english.
Thanks admin, it is really helpful and your coding gives clear explanation. Share more like this.
ReplyDeleteAngular 2 Training in Chennai | Angular 4 Training in Chennai
Hi ,
ReplyDeleteThank you for this tutorial and I have a question. My app is working well but when I am searching something on the searchbar I can not find the cities. I am able to see just unrelated places. For example if I am writing "Warsaw" first thing I am seeing Warsaw street at
hello dear im using this map in angular 4 ang getting error like
ReplyDeletecore.js:1440 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
at eval (adddepot.component.ts:162)
at ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:4733)
at ZoneDelegate.invoke (zone.js:387)
at Zone.run (zone.js:138)
at eval (zone.js:858)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4724)
at ZoneDelegate.invokeTask (zone.js:420)
any solution
Hello,
ReplyDeleteI have an error, "google is undefined".
How can I solve this ?
Adrian
Hi Dear,
ReplyDeletei am facing this error
"Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error"
If you want to use google maps api, you must have a key. Look here: https://developers.google.com/maps/documentation/javascript/get-api-key
DeleteThanks Dear.
DeleteInvalidValueError: not an instance of HTMLInputElement
ReplyDeleteplease this is the error i get when i used you tuto... thanks for the tuto though
Did you find the answer to this? I can't get the answer anywhere
DeleteI had the same error
DeleteInvalidValueError: not an instance of HTMLInputElement
in my Angular 5 project with using AGM (Angular Google Maps) and can't solve this problem...
great blog,Thank you for sharing such a wonderful information..keep sharing
ReplyDeleteAngular 5 online training
Angular 5 training in hyderabad
Thank you for the great blog ,
ReplyDeleteI followed all of your steps
But I`m getting this error https://www.diigo.com/item/image/52mls/o6h9
I`m using angular 6
scraped all over internet but no solution.
in my chrome dev tools i see this error -> Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined
This npm package working in 2018 ?
It is nice blog Thank you provide important information and i am searching for same information to save my time AngularJS Online Training
ReplyDeletenice blog. Thanku you so much for your help
ReplyDeletethank u..
ReplyDeleteHi, wow, your tutorial is very powerful! , I would like to know how I could get a value selected?
ReplyDeleteThank you very much!
public selected: string;
DeleteI got the solution
into the onInit()
this.selected = place.adr_address;
console.log(place);
I've another question... I would like to know how I could restrict the search to one area, for example, Spain ... (country) or Madrid(State) ....
Hello Dante , Have you found the way to restrict the range of the search ???
Deleteanswer to my self: you need to spicify a LatLngBounds Object wich is a square to restrict the area and passing to the Autocomplete method inside the option paramater, this is an example for spain... (not too exact the area)
Deleteconst defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(27.633333, -18.166667),
new google.maps.LatLng(38.934712, 4.920626)
/*meters*/);
const options = {
types: [], // this remove the type restriction
defaultBounds: defaultBounds
};
const autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, options);
Those guidelines additionally worked to become a good way to recognize that other people online have the identical fervor like mine to grasp great deal more around this condition. we are providing AngularJs training in velachery.
ReplyDeletefor more details:AngularJs training in velachery
I would like to greatly appreciate your interest in sharing the info with us. Continue with more recent updates.
ReplyDeleteSpoken English Classes in Ayanavaram
Spoken English Class in Mogappair
Spoken English Classes in St.Thomas Mount
Spoken English Training in DLF
Spoken English Class in T-Nagar Chennai
English Coaching Classes in T-Nagar
Spoken English Training in Kasturibai Nagar
Spoken English Classes in Ecr
hi Abhisek , how to create legend on Angular google map??
ReplyDeletethanks in advance...
ReplyDeleteSearch autocomplete not working in popup modal
core.js:15713 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined
how to use for multiple inputs
ReplyDeletehello i got this error
ReplyDeleteUncaught (in promise): TypeError: _this.searchElementRef is undefined
./src/app/components/property-owner/property-owner.component.ts
have any solution for this?
Nice article. I really love your information very much.
ReplyDeleteAngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery