Google Maps v3 API - Auto Complete (address)

Viewed 49073

Attempting to get auto complete working for my google maps application.

Here is the current code:

HTML

<input type="text" class="clearText" id="address" name="address" value="" size=20 autocomplete="off">

Javascript

    var input = document.getElementById('address');
    var options = {
        componentRestrictions: {country: 'au'}
    };
    var autocomplete = new google.maps.places.Autocomplete(input, options);

Unfortunately nothing happens when typing an address.

Any ideas?

Thanks in advance.

Edit: I'm actually receiving the following error:

Uncaught TypeError: Cannot read property 'autocomplete' of undefined

Not sure why, the code is placed in my map initialize function.

Edit 2: Fixed. Answer below.

8 Answers

Since this question helped me I figured I would help anyonewho is having this problem in 2019. In 2019 you add the google maps api import like this:

https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY

Then add &libraries=places to the end so that all said and done it looks like this:

<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&libraries=places">
</script>

if you are using angular app:

If you are using google maps you have to import the Api in the ngmodule like this

@NgModule({
  declarations: [...],
  imports: [...,
    AgmCoreModule.forRoot({
      clientId: '<mandatory>',
      //apiVersion: 'xxx', // optional
      //channel: 'yyy', // optional
      //apiKey: 'zzz', // optional
      language: 'en',
      libraries: ['geometry', 'places']
    })
  ],
  providers: [...],
  bootstrap: [...]
})

the library 'places' is needed to use the autocomplete module.

Than use it like this:

import {MapsAPILoader} from "@agm/core";
...
constructor(private mapsAPILoader: MapsAPILoader,
...
    this.mapsAPILoader.load().then(() => {
      let autocomplete = new window['google'].maps.places.Autocomplete(..., ...);

      autocomplete.addListener("place_changed", () => { ...

i found this error because of my API key have exceeded daily request quota for this API.

i just create new API key and Replace it instead of old one.

it works for me

thank you

In my case issue was resolve by changing the Libraries=places to libraries=places it seems to be case sensitive

Related