Matt
Matt

Reputation: 1580

Google Maps v3 API - Auto Complete (address)

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.

Upvotes: 45

Views: 49668

Answers (9)

Cloudberry
Cloudberry

Reputation: 1

There is an example using Javascript for the (old) Places API at https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

The javascript code is as follows:

// This sample uses the Places Autocomplete widget to:
// 1. Help the user select a place
// 2. Retrieve the address components associated with that place
// 3. Populate the form fields with those address components.
// This sample requires the Places library, Maps JavaScript API.
// Include the libraries=places parameter when you first load the API.
// For example: <script
// src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
let autocomplete;
let address1Field;
let address2Field;
let postalField;

function initAutocomplete() {
  address1Field = document.querySelector("#ship-address");
  address2Field = document.querySelector("#address2");
  postalField = document.querySelector("#postcode");
  // Create the autocomplete object, restricting the search predictions to
  // addresses in the US and Canada.
  autocomplete = new google.maps.places.Autocomplete(address1Field, {
    componentRestrictions: { country: ["us", "ca"] },
    fields: ["address_components", "geometry"],
types: ["address"],
  });
  address1Field.focus();
  // When the user selects an address from the drop-down, populate the
  // address fields in the form.
   autocomplete.addListener("place_changed", fillInAddress);
}
function fillInAddress() {
  // Get the place details from the autocomplete object.
  const place = autocomplete.getPlace();
  let address1 = "";
  let postcode = "";

  // Get each component of the address from the place details,
  // and then fill-in the corresponding field on the form.
  // place.address_components are google.maps.GeocoderAddressComponent objects
  // which are documented at http://goo.gle/3l5i5Mr
  for (const component of place.address_components) {
    // @ts-ignore remove once typings fixed
    const componentType = component.types[0];

    switch (componentType) {
      case "street_number": {
    address1 = `${component.long_name} ${address1}`;
        break;
      }

  case "route": {
    address1 += component.short_name;
    break;
  }

  case "postal_code": {
    postcode = `${component.long_name}${postcode}`;
    break;
  }

  case "postal_code_suffix": {
    postcode = `${postcode}-${component.long_name}`;
    break;
  }
  case "locality":
    document.querySelector("#locality").value = component.long_name;
        break;
      case "administrative_area_level_1": {
    document.querySelector("#state").value = component.short_name;
    break;
  }
  case "country":
    document.querySelector("#country").value = component.long_name;
    break;
    }
  }
  address1Field.value = address1;
  postalField.value = postcode;
  // After filling the form with address components from the Autocomplete
  // prediction, set cursor focus on the second address line to encourage
  // entry of subpremise information such as apartment, unit, or floor number.
  address2Field.focus();
}

window.initAutocomplete = initAutocomplete;

The call to the API is commented out and should also be included.

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

Notes

This may generate a deprecated code warning for autocomplete.addListener but it still works.

Google's billing system is changing as of March 2025 so the free $200 a month credit may no longer apply. There will be a free call allowance for the Places (New) API, but so far I haven't found a working example of address autocomplete for the 'new' API.

Upvotes: 0

mayorvlf
mayorvlf

Reputation: 1

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

Upvotes: 0

Caleb
Caleb

Reputation: 621

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>

Upvotes: 9

vinayak surywanshi
vinayak surywanshi

Reputation: 81

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

Upvotes: 0

Kesara Wimal
Kesara Wimal

Reputation: 729

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

Upvotes: 5

Matt
Matt

Reputation: 1580

Fixed. The autocomplete library is actually a separate library that must be explicitly loaded. The following line solved the problem.

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places‌​&sensor=false"></scr‌​ipt>

Upvotes: 10

Mohammed Mukhtar
Mohammed Mukhtar

Reputation: 1741

You have to add 'defer async' to the script attribute, like this:

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

Upvotes: 1

davke
davke

Reputation: 360

Thanks Matt for the answer! Somehow it seems to be important not to omit type="text/javascript" attribute on <script> tag when using libraries=places.

Doesn't work:

<script src="http://maps.googleapis.com/maps/api/js?libaries=places&sensor=false&callback=initMap"></script>
<script src="http://maps.googleapis.com/maps/api/js?libaries=places&sensor=false"></script>

Works:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>

Callback variant also works (with initMap function defined):

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&callback=initMap"></script>

This seems to be consistent with another SO answer and inconsistent with the official documentation (unless providing the key in the url makes the difference).

Upvotes: 0

Hung Luu
Hung Luu

Reputation: 1123

Your fix worked for me too. I'm using the Geocomplete jQuery Plug-in http://ubilabs.github.com/geocomplete/ and the instructions on their home page says to use this

<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>

But it didn't work for me and was getting the same error.

See documentation for Google Maps API here https://developers.google.com/maps/documentation/javascript/places?hl=en-EN#loading_the_library

Upvotes: 21

Related Questions