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.

  1. npm install @angular/cli -g
  2. ng new my-app
  3. cd my-app
  4. 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.


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.



 

And Do visit this page for more Javacript posts.

Thank You. 


Comments

  1. Thank You for posting this stuff.

    It is very helpful . Also the video is well structured.

    Keep up the good work. Waiting for more stuff from your side.

    ReplyDelete
  2. I am having this problem
    http://imgur.com/a/yy7Di

    ReplyDelete
    Replies
    1. got the error....my api key was not valid

      Delete
    2. Good!!

      Do Comment If You Face any issue.

      Delete
  3. ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'Autocomplete' of undefined

    ReplyDelete
    Replies
    1. Hi Victor,

      Make sure you have this import:

      import {} from '@types/googlemaps';

      and do comment if you face any issue further.

      Delete



  4. Abhishek can you suggest any book or site from where I can learn angular 2.

    ReplyDelete
    Replies
    1. Hi,

      For 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.

      Delete
    2. Thanks and do keep posting new videos
      For the above code I got this error :
      Property 'auto complete' does not exist on type 'typeof places'

      Delete
    3. Make sure you have this import:

      import {} from '@types/googlemaps';

      and do comment if you face any issue further.

      Delete
    4. also 'A' of autocomplete is in caps

      Delete
    5. Still not working

      https://drive.google.com/open?id=0BzBD-JCZBacJbnJGajNhX0R1UEk

      Delete
    6. it showing error here:: import { } from '@types/googlemaps'; that index.d.ts is not a module. can you please help

      Delete
  5. How I can get data(token ) from third party login window and save it using angular js 2
    Or
    How I can control third party window through script

    ReplyDelete
  6. 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.

    ReplyDelete
  7. hello there!

    i 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!

    ReplyDelete
    Replies
    1. i figured it out!

      you have to bind the search variable via document.body.getElementsByTagName('input')[0]

      what a run-around! thanks again for the tutorials!

      Delete
  8. How can I get the latitude and longitude of the address searched?

    ReplyDelete
    Replies
    1. JSON.stringify(place.geometry.location);

      Delete
    2. please can u send full code to get the latitude and longitude of the address searched.

      Delete
    3. This comment has been removed by the author.

      Delete
  9. Hi thanks for tutorial but i have in console warning:
    You 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!

    ReplyDelete
  10. I have this error:

    Uncaught (in promise): TypeError: Cannot read property 'nativeElement' of undefined
    TypeError: Cannot read property 'nativeElement' of undefined

    ReplyDelete
    Replies
    1. I think the problem is because my form this opens in a modal with templateref :/

      Delete
  11. Hello Thanks very much for that tuto. (it help me also to use the DistanceMatrixService)

    Still 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.

    ReplyDelete
  12. Thanks admin, it is really helpful and your coding gives clear explanation. Share more like this.
    Angular 2 Training in Chennai | Angular 4 Training in Chennai

    ReplyDelete
  13. Hi ,
    Thank 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

    ReplyDelete
  14. hello dear im using this map in angular 4 ang getting error like


    core.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

    ReplyDelete
  15. Hello,

    I have an error, "google is undefined".
    How can I solve this ?

    Adrian

    ReplyDelete
  16. Hi Dear,

    i am facing this error

    "Google Maps API error: InvalidKeyMapError https://developers.google.com/maps/documentation/javascript/error-messages#invalid-key-map-error"

    ReplyDelete
    Replies
    1. 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

      Delete
  17. InvalidValueError: not an instance of HTMLInputElement

    please this is the error i get when i used you tuto... thanks for the tuto though

    ReplyDelete
    Replies
    1. Did you find the answer to this? I can't get the answer anywhere

      Delete
    2. I had the same error
      InvalidValueError: not an instance of HTMLInputElement
      in my Angular 5 project with using AGM (Angular Google Maps) and can't solve this problem...

      Delete
  18. great blog,Thank you for sharing such a wonderful information..keep sharing
    Angular 5 online training
    Angular 5 training in hyderabad

    ReplyDelete
  19. Thank you for the great blog ,
    I 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 ?

    ReplyDelete
  20. It is nice blog Thank you provide important information and i am searching for same information to save my time AngularJS Online Training

    ReplyDelete
  21. nice blog. Thanku you so much for your help

    ReplyDelete
  22. Hi, wow, your tutorial is very powerful! , I would like to know how I could get a value selected?

    Thank you very much!

    ReplyDelete
    Replies
    1. public selected: string;

      I 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) ....

      Delete
    2. Hello Dante , Have you found the way to restrict the range of the search ???

      Delete
    3. answer 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)

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

      Delete
  23. 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.
    for more details:AngularJs training in velachery

    ReplyDelete
  24. hi Abhisek , how to create legend on Angular google map??
    thanks in advance...

    ReplyDelete

  25. Search 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

    ReplyDelete
  26. how to use for multiple inputs

    ReplyDelete
  27. hello i got this error
    Uncaught (in promise): TypeError: _this.searchElementRef is undefined
    ./src/app/components/property-owner/property-owner.component.ts
    have any solution for this?

    ReplyDelete

Post a Comment

Popular posts from this blog

Range Slider Uisng Javascript and CSS for changing the selected part Color

[Sass] Installing and Using Sass on Windows for Beginners