Ionic Google Autocomplete Uncaught Typeerror: Cannot Read Property 'foreach' of Null

Introduction

Autocomplete is a feature of the Places library in the Maps JavaScript API. You lot can employ autocomplete to give your applications the blazon-ahead-search beliefs of the Google Maps search field. The autocomplete service can friction match on full words and substrings, resolving place names, addresses, and plus codes. Applications can therefore send queries equally the user types, to provide on-the-wing identify predictions.

Getting started

Before using the Places library in the Maps JavaScript API, first ensure that the Places API is enabled in the Google Cloud Panel, in the same project yous set up for the Maps JavaScript API.

To view your list of enabled APIs:

  1. Become to the Google Cloud Console.
  2. Click the Select a project button, then select the aforementioned projection you ready for the Maps JavaScript API and click Open.
  3. From the list of APIs on the Dashboard, look for Places API.
  4. If you come across the API in the listing, you're all set. If the API is not listed, enable it:
    1. At the meridian of the page, select ENABLE API to display the Library tab. Alternatively, from the left side menu, select Library.
    2. Search for Places API, then select information technology from the results listing.
    3. Select ENABLE. When the procedure finishes, Places API appears in the list of APIs on the Dashboard.

Loading the library

The Places service is a self-contained library, separate from the primary Maps JavaScript API code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:

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

See the Libraries Overview for more information.

Summary of classes

The API offers two types of autocomplete widgets, which you can add via the Autocomplete and SearchBox classes respectively. In addition, you lot can use the AutocompleteService class to think autocomplete results programmatically (see the Maps JavaScript API Reference: AutocompleteService class).

Beneath is a summary of the classes available:

  • Autocomplete adds a text input field to your web page, and monitors that field for grapheme entries. As the user enters text, autocomplete returns identify predictions in the class of a dropdown pick list. When the user selects a place from the list, information about the place is returned to the autocomplete object, and can exist retrieved by your application. Come across the details below.
    An autocomplete text field, and the pick list of place      predictions supplied as the user enters the search query.
    Effigy 1: Autocomplete text field and pick listing
    A completed address form.
    Figure 2: Completed address class
  • SearchBox adds a text input field to your web page, in much the same fashion as Autocomplete. The differences are as follows:
    • The main departure lies in the results that announced in the option list. SearchBox supplies an extended list of predictions, which tin can include places (as defined by the Places API) plus suggested search terms. For example, if the user enters 'pizza in new', the pick listing may include the phrase 'pizza in New York, NY' as well as the names of various pizza outlets.
    • SearchBox offers fewer options than Autocomplete for restricting the search. In the former, you tin can bias the search towards a given LatLngBounds. In the latter, you can restrict the search to a particular country and particular place types, as well as setting the premises. For more information, see below.
    A completed address form.
    Figure 3: A SearchBox presents search terms and place predictions.
    See the details below.
  • You tin can create an AutocompleteService object to call back predictions programmatically. Call getPlacePredictions() to retrieve matching places, or telephone call getQueryPredictions() to think matching places plus suggested search terms. Annotation: AutocompleteService does not add any UI controls. Instead, the higher up methods render an array of prediction objects. Each prediction object contains the text of the prediction, besides equally reference information and details of how the result matches the user input. Run across the details below.

Calculation an Autocomplete widget

The Autocomplete widget creates a text input field on your spider web page, supplies predictions of places in a UI choice listing, and returns place details in response to a getPlace() asking. Each entry in the pick list corresponds to a single place (as defined by the Places API).

The Autocomplete constructor takes two arguments:

  • An HTML input chemical element of type text. This is the input field that the autocomplete service will monitor and attach its results to.
  • An optional AutocompleteOptions argument, which can contain the post-obit properties:
    • An array of information fields to be included in the Place Details response for the user's selected PlaceResult. If the property is not set or if ['ALL'] is passed in, all available fields are returned and billed for (this is not recommended for production deployments). For a list of fields, see PlaceResult.
    • An array of types that specifies an explicit blazon or a type collection, as listed in the supported types. If no type is specified, all types are returned.
    • premises is a google.maps.LatLngBounds object specifying the expanse in which to search for places. The results are biased towards, simply non restricted to, places contained within these bounds.
    • strictBounds is a boolean specifying whether the API must render only those places that are strictly within the region defined past the given bounds. The API does not return results outside this region even if they friction match the user input.
    • componentRestrictions can be used to restrict results to specific groups. Currently, you lot tin can use componentRestrictions to filter by up to 5 countries. Countries must be passed equally every bit a two-character, ISO 3166-i Alpha-2 uniform country code. Multiple countries must exist passed equally a list of country codes.

      Note: If you receive unexpected results with a country code, verify that you are using a code which includes the countries, dependent territories, and special areas of geographical involvement you intend. You lot tin find code data at Wikipedia: List of ISO 3166 country codes or the ISO Online Browsing Platform.

    • placeIdOnly can be used to instruct the Autocomplete widget to retrieve but Identify IDs. On calling getPlace() on the Autocomplete object, the PlaceResult made available will only have the place id, types and name properties gear up. You can use the returned place ID with calls to the Places, Geocoding, Directions or Distance Matrix services.

Constraining Autocomplete predictions

Past default, Place Autocomplete presents all identify types, biased for predictions most the user'southward location, and fetches all available information fields for the user's selected place. Prepare Place Autocomplete options to present more relevant predictions based on your use case.

Set options at construction

The Autocomplete constructor accepts an AutocompleteOptions parameter to set up constraints at widget creation. The following example sets the premises, componentRestrictions, and types options to request establishment blazon places, favoring those within the specified geographic area and restricting predictions to only places inside the United states. Setting the fields option specifies what data to return nigh the user's selected place.

Call setOptions() to change an option's value for an existing widget.

TypeScript

const center = { lat: 50.064192, lng: -130.605469 }; // Create a bounding box with sides ~10km away from the middle point const defaultBounds = {   n: heart.lat + 0.1,   south: center.lat - 0.1,   east: centre.lng + 0.i,   westward: center.lng - 0.1, }; const input = certificate.getElementById("pac-input") as HTMLInputElement; const options = {   bounds: defaultBounds,   componentRestrictions: { country: "us" },   fields: ["address_components", "geometry", "icon", "name"],   strictBounds: false,   types: ["establishment"], };  const autocomplete = new google.maps.places.Autocomplete(input, options);

JavaScript

const heart = { lat: fifty.064192, lng: -130.605469 }; // Create a bounding box with sides ~10km away from the center point const defaultBounds = {   north: centre.lat + 0.1,   s: center.lat - 0.ane,   east: center.lng + 0.1,   w: center.lng - 0.1, }; const input = document.getElementById("pac-input"); const options = {   premises: defaultBounds,   componentRestrictions: { land: "united states" },   fields: ["address_components", "geometry", "icon", "proper noun"],   strictBounds: false,   types: ["establishment"], }; const autocomplete = new google.maps.places.Autocomplete(input, options);            

Specify data fields

Specify data fields to avert being billed for Places Data SKUs y'all don't need. Include the fields property in the AutocompleteOptions that are passed to the widget constructor, every bit demonstrated in the previous case, or call setFields() on an existing Autocomplete object.

autocomplete.setFields(["place_id", "geometry", "name"]);        

Define biases and search-area boundaries for Autocomplete

Y'all tin bias the autocomplete results to favor an approximate location or surface area, in the following means:

  • Set the bounds on creation of the Autocomplete object.
  • Change the premises on an existing Autocomplete.
  • Fix the premises to the map's viewport.
  • Restrict the search to the bounds.
  • Restrict the search to a specific state.

The previous example demonstrates setting premises at cosmos. The following examples demonstrate the other biasing techniques.

Change the premises of an existing Autocomplete

Call setBounds() to alter the search expanse on an existing Autocomplete to rectangular bounds.

TypeScript

const southwest = { lat: 5.6108, lng: 136.589326 }; const northeast = { lat: 61.179287, lng: ii.64325 }; const newBounds = new google.maps.LatLngBounds(southwest, northeast);  autocomplete.setBounds(newBounds);

JavaScript

const southwest = { lat: v.6108, lng: 136.589326 }; const northeast = { lat: 61.179287, lng: 2.64325 }; const newBounds = new google.maps.LatLngBounds(southwest, northeast);  autocomplete.setBounds(newBounds);            
Set the bounds to the map's viewport

Use bindTo() to bias the results to the map'southward viewport, even while that viewport changes.

TypeScript

autocomplete.bindTo("bounds", map);

JavaScript

autocomplete.bindTo("bounds", map);            

Use unbind() to unbind the Autocomplete predictions from the map's viewport.

TypeScript

autocomplete.unbind("bounds"); autocomplete.setBounds({ east: 180, west: -180, north: ninety, s: -90 });

JavaScript

autocomplete.unbind("bounds"); autocomplete.setBounds({ east: 180, west: -180, north: 90, south: -90 });

View example

Restrict the search to the current bounds

Ready the strictBounds option to restrict the results to the electric current bounds, whether based on map viewport or rectangular bounds.

autocomplete.setOptions({ strictBounds: truthful });        
Restrict predictions to a specific state

Use the componentRestrictions option or call setComponentRestrictions() to restrict the autocomplete search to a specific set of up to five countries.

TypeScript

autocomplete.setComponentRestrictions({   country: ["the states", "pr", "vi", "gu", "mp"], });

JavaScript

autocomplete.setComponentRestrictions({   state: ["us", "pr", "vi", "gu", "mp"], });            

View example

Constrain place types

Utilise the types option or telephone call setTypes() to restrict predictions to certain place types. The Places Autocomplete demo demonstrates the differences in predictions betwixt different place types. See types supported in identify autocomplete requests for an explanation of supported values for this belongings.

Visit demo

Getting identify information

When a user selects a place from the predictions attached to the autocomplete text field, the service fires a place_changed consequence. To get place details:

  1. Create an event handler for the place_changed upshot, and telephone call addListener() on the Autocomplete object to add together the handler.
  2. Phone call Autocomplete.getPlace() on the Autocomplete object, to retrieve a PlaceResult object, which you tin then use to get more data nearly the selected place.

By default, when a user selects a place, autocomplete returns all of the bachelor data fields for the selected place, and you will be billed appropriately. Use Autocomplete.setFields() to specify which place data fields to return. Read more about the PlaceResult object, including a listing of identify data fields that you can request. To avoid paying for data that you don't need, be sure to utilise Autocomplete.setFields() to specify only the place data that you will use.

The proper name property contains the description from Places Autocomplete predictions. Yous can read more nearly the description in the Places Autocomplete documentation.

For accost forms, information technology is useful to get the address in structured format. To render the structured address for the selected place, call Autocomplete.setFields() and specify the address_components field.

The following example uses autocomplete to fill the fields in an address class.

TypeScript

function fillInAddress() {   // Get the identify details from the autocomplete object.   const place = autocomplete.getPlace();   permit address1 = "";   let postcode = "";    // Become each component of the address from the place details,   // so backup 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 every bit google.maps.GeocoderAddressComponent[]) {     // @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;         intermission;       }        case "postal_code": {         postcode = `${component.long_name}${postcode}`;         interruption;       }        example "postal_code_suffix": {         postcode = `${postcode}-${component.long_name}`;         break;       }        instance "locality":         (document.querySelector("#locality") as HTMLInputElement).value =           component.long_name;         break;        case "administrative_area_level_1": {         (document.querySelector("#state") equally HTMLInputElement).value =           component.short_name;         break;       }        case "country":         (document.querySelector("#country") as HTMLInputElement).value =           component.long_name;         break;     }   }    address1Field.value = address1;   postalField.value = postcode;    // Afterward filling the class with address components from the Autocomplete   // prediction, prepare cursor focus on the 2d address line to encourage   // entry of subpremise information such as flat, unit of measurement, or flooring number.   address2Field.focus(); }

JavaScript

function fillInAddress() {   // Get the place details from the autocomplete object.   const identify = autocomplete.getPlace();   permit address1 = "";   allow postcode = "";    // Get each component of the address from the place details,   // and and then make full-in the corresponding field on the form.   // identify.address_components are google.maps.GeocoderAddressComponent objects   // which are documented at http://goo.gle/3l5i5Mr   for (const component of place.address_components) {     const componentType = component.types[0];      switch (componentType) {       case "street_number": {         address1 = `${component.long_name} ${address1}`;         break;       }        case "route": {         address1 += component.short_name;         break;       }        instance "postal_code": {         postcode = `${component.long_name}${postcode}`;         intermission;       }        example "postal_code_suffix": {         postcode = `${postcode}-${component.long_name}`;         break;       }       instance "locality":         document.querySelector("#locality").value = component.long_name;         intermission;       instance "administrative_area_level_1": {         document.querySelector("#state").value = component.short_name;         break;       }       case "country":         document.querySelector("#country").value = component.long_name;         interruption;     }   }    address1Field.value = address1;   postalField.value = postcode;   // After filling the form with address components from the Autocomplete   // prediction, prepare cursor focus on the second address line to encourage   // entry of subpremise information such equally flat, unit, or floor number.   address2Field.focus(); }

View case

Customizing placeholder text

Past default, the text field created by the autocomplete service contains standard placeholder text. To modify the text, fix the placeholder attribute on the input element:

<input id="searchTextField" type="text" size="50" placeholder="Anything you want!">

Notation: The default placeholder text is localized automatically. If you lot specify your ain placeholder value, you must handle the localization of that value in your awarding. For information on how the Google Maps JavaScript API chooses the language to use, please read the documentation on localization.

See Styling the Autocomplete and SearchBox widgets to customize the widget appearance.

The SearchBox allows users to perform a text-based geographic search, such as 'pizza in New York' or 'shoe stores near robson street'. You can adhere the SearchBox to a text field and, every bit text is entered, the service will render predictions in the course of a drop-down pick list.

SearchBox supplies an extended list of predictions, which tin include places (as defined by the Places API) plus suggested search terms. For instance, if the user enters 'pizza in new', the choice list may include the phrase 'pizza in New York, NY' also every bit the names of various pizza outlets. When a user selects a place from the list, information about that place is returned to the SearchBox object, and tin exist retrieved by your awarding.

The SearchBox constructor takes two arguments:

  • An HTML input element of type text. This is the input field that the SearchBox service will monitor and attach its results to.
  • An options statement, which tin can contain the premises property: bounds is a google.maps.LatLngBounds object specifying the expanse in which to search for places. The results are biased towards, but non restricted to, places independent within these bounds.

The post-obit lawmaking uses the bounds parameter to bias the results towards places inside a particular geographic surface area, specified via laitude/longitude coordinates.

var defaultBounds = new google.maps.LatLngBounds(   new google.maps.LatLng(-33.8902, 151.1759),   new google.maps.LatLng(-33.8474, 151.2631));  var input = document.getElementById('searchTextField');  var searchBox = new google.maps.places.SearchBox(input, {   bounds: defaultBounds });        

Changing the search surface area for SearchBox

To change the search expanse for an existing SearchBox, phone call setBounds() on the SearchBox object and laissez passer the relevant LatLngBounds object.

View example

Getting place information

When the user selects an item from the predictions attached to the search box, the service fires a places_changed event. Yous can telephone call getPlaces() on the SearchBox object, to think an array containing several predictions, each of which is a PlaceResult object.

For more than information about the PlaceResult object, refer to the documentation on identify detail results.

TypeScript

// Heed for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener("places_changed", () => {   const places = searchBox.getPlaces();    if (places.length == 0) {     return;   }    // Clear out the old markers.   markers.forEach((marking) => {     marking.setMap(null);   });   markers = [];    // For each place, go the icon, name and location.   const bounds = new google.maps.LatLngBounds();    places.forEach((place) => {     if (!place.geometry || !place.geometry.location) {       console.log("Returned identify contains no geometry");       render;     }      const icon = {       url: place.icon as string,       size: new google.maps.Size(71, 71),       origin: new google.maps.Bespeak(0, 0),       anchor: new google.maps.Point(17, 34),       scaledSize: new google.maps.Size(25, 25),     };      // Create a marker for each identify.     markers.push(       new google.maps.Marking({         map,         icon,         championship: place.name,         position: place.geometry.location,       })     );      if (place.geometry.viewport) {       // Simply geocodes have viewport.       bounds.union(place.geometry.viewport);     } else {       premises.extend(place.geometry.location);     }   });   map.fitBounds(bounds); });

JavaScript

// Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener("places_changed", () => {   const places = searchBox.getPlaces();    if (places.length == 0) {     render;   }    // Articulate out the erstwhile markers.   markers.forEach((marker) => {     marker.setMap(null);   });   markers = [];    // For each identify, become the icon, proper name and location.   const bounds = new google.maps.LatLngBounds();    places.forEach((place) => {     if (!place.geometry || !place.geometry.location) {       console.log("Returned place contains no geometry");       return;     }      const icon = {       url: place.icon,       size: new google.maps.Size(71, 71),       origin: new google.maps.Signal(0, 0),       anchor: new google.maps.Signal(17, 34),       scaledSize: new google.maps.Size(25, 25),     };      // Create a marker for each identify.     markers.push(       new google.maps.Marker({         map,         icon,         championship: place.proper noun,         position: identify.geometry.location,       })     );     if (identify.geometry.viewport) {       // Only geocodes take viewport.       bounds.union(place.geometry.viewport);     } else {       bounds.extend(identify.geometry.location);     }   });   map.fitBounds(bounds); });

View case

Meet Styling the Autocomplete and SearchBox widgets to customize the widget appearance.

Programmatically retrieving Place Autocomplete Service predictions

To think predictions programmatically, use the AutocompleteService class. AutocompleteService does not add together any UI controls. Instead, it returns an array of prediction objects, each containing the text of the prediction, reference information, and details of how the event matches the user input. This is useful if you desire more control over the user interface than is offered by the Autocomplete and SearchBox described above.

AutocompleteService exposes the following methods:

  • getPlacePredictions() returns place predictions. Note: A 'place' can be an establishment, geographic location, or prominent point of interest, as defined by the Places API.
  • getQueryPredictions() returns an extended list of predictions, which can include places (as defined by the Places API) plus suggested search terms. For instance, if the user enters 'pizza in new', the choice list may include the phrase 'pizza in New York, NY' likewise equally the names of various pizza outlets.

Both of the above methods return an assortment of prediction objects of the post-obit form:

  • clarification is the matched prediction.
  • distance_meters is the distance in meters of the identify from the specified AutocompletionRequest.origin.
  • matched_substrings contains a fix of substrings in the description that lucifer elements in the user's input. This is useful for highlighting those substrings in your application. In many cases, the query will appear as a substring of the description field.
    • length is the length of the substring.
    • offset is the grapheme offset, measured from the offset of the clarification cord, at which the matched substring appears.
  • place_id is a textual identifier that uniquely identifies a place. To retrieve information about the identify, pass this identifier in the placeId field of a Place Details request. Learn more about how to reference a place with a place ID.
  • terms is an array containing elements of the query. For a place, each element will typically make up a portion of the address.
    • get-go is the character starting time, measured from the commencement of the clarification string, at which the matched substring appears.
    • value is the matching term.

The case beneath executes a query prediction request for the phrase 'pizza nearly' and displays the result in a list.

TypeScript

// This case retrieves autocomplete predictions programmatically from the // autocomplete service, and displays them equally an HTML list. // This example requires the Places library. Include the libraries=places // parameter when y'all get-go load the API. For instance: // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> function initService(): void {   const displaySuggestions = function (     predictions: google.maps.places.QueryAutocompletePrediction[] | zip,     status: google.maps.places.PlacesServiceStatus   ) {     if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) {       alarm(condition);       render;     }      predictions.forEach((prediction) => {       const li = document.createElement("li");        li.appendChild(document.createTextNode(prediction.clarification));       (document.getElementById("results") equally HTMLUListElement).appendChild(li);     });   };    const service = new google.maps.places.AutocompleteService();    service.getQueryPredictions({ input: "pizza near Syd" }, displaySuggestions); }

JavaScript

// This example retrieves autocomplete predictions programmatically from the // autocomplete service, and displays them equally an HTML list. // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?cardinal=YOUR_API_KEY&libraries=places"> office initService() {   const displaySuggestions = function (predictions, condition) {     if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) {       alarm(status);       return;     }      predictions.forEach((prediction) => {       const li = certificate.createElement("li");        li.appendChild(document.createTextNode(prediction.clarification));       certificate.getElementById("results").appendChild(li);     });   };    const service = new google.maps.places.AutocompleteService();    service.getQueryPredictions({ input: "pizza nigh Syd" }, displaySuggestions); }              

CSS

            

HTML

<!DOCTYPE html> <html>   <head>     <title>Retrieving Autocomplete Predictions</title>     <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>     <link rel="stylesheet" type="text/css" href="./style.css" />     <script src="./alphabetize.js"></script>   </head>   <torso>     <p>Query suggestions for 'pizza most Syd':</p>     <ul id="results"></ul>      <!-- Async script executes immediately and must be after whatsoever DOM elements used in callback. -->     <script       src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initService&libraries=places&v=weekly"       async     ></script>   </body> </html>

// This case retrieves autocomplete predictions programmatically from the // autocomplete service, and displays them as an HTML listing. // This example requires the Places library. Include the libraries=places // parameter when yous first load the API. For example: // <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&libraries=places"> part initService() { const displaySuggestions = function (predictions, condition) { if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) { alert(status); return; } predictions.forEach((prediction) => { const li = document.createElement("li"); li.appendChild(document.createTextNode(prediction.description)); document.getElementById("results").appendChild(li); }); }; const service = new google.maps.places.AutocompleteService(); service.getQueryPredictions({ input: "pizza most Syd" }, displaySuggestions); }

<!DOCTYPE html> <html> <head> <title>Retrieving Autocomplete Predictions</championship> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <!-- jsFiddle will insert css and js --> </caput> <body> <p>Query suggestions for 'pizza near Syd':</p> <ul id="results"></ul> <!-- Async script executes immediately and must exist later on any DOM elements used in callback. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initService&libraries=places&v=weekly&channel=two" async ></script> </body> </html>

Try Sample

View example

Session tokens

AutocompleteService.getPlacePredictions() uses session tokens to group together autocomplete requests for billing purposes. Session tokens group the query and choice phases of a user autocomplete search into a discrete session for billing purposes. The session begins when the user starts typing a query, and concludes when they select a identify. Each session can have multiple queries, followed by one identify selection. One time a session has concluded, the token is no longer valid. Your app must generate a fresh token for each session. We recommend using session tokens for all autocomplete sessions. If the sessionToken parameter is omitted, or if yous reuse a session token, the session is charged as if no session token was provided (each request is billed separately).

You can use the same session token to make a unmarried Place Details request on the place that results from a call to AutocompleteService.getPlacePredictions(). In this case, the autocomplete request is combined with the Place Details request, and the telephone call is charged as a regular Place Details request. There is no accuse for the autocomplete asking.

Be sure to laissez passer a unique session token for each new session. Using the same token for more one Autocomplete session volition invalidate those Autocomplete sessions, and all Autocomplete request in the invalid sessions will exist charged individually using Autocomplete Per Asking SKU. Read more about session tokens.

The post-obit example shows creating a session token, and so passing it in an AutocompleteService (the displaySuggestions() function has been omitted for brevity):

// Create a new session token. var sessionToken = new google.maps.places.AutocompleteSessionToken();  // Pass the token to the autocomplete service. var autocompleteService = new google.maps.places.AutocompleteService(); autocompleteService.getPlacePredictions({   input: 'pizza near Syd',   sessionToken: sessionToken }, displaySuggestions);        

Be certain to pass a unique session token for each new session. Using the aforementioned token for more one session volition result in each request existence billed individually.

Read more than well-nigh session tokens.

Styling the Autocomplete and SearchBox widgets

Past default, the UI elements provided by Autocomplete and SearchBox are styled for inclusion on a Google map. You lot may want to adjust the styling to adapt your own site. The post-obit CSS classes are available. All classes listed beneath apply to both the Autocomplete and the SearchBox widgets.

A graphical illustration of the CSS classes for the Autocomplete and        SearchBox widgets
CSS classes for Autocomplete and SearchBox widgets
CSS course Clarification
pac-container The visual chemical element containing the listing of predictions returned by the Place Autocomplete service. This list appears equally a dropdown list below the Autocomplete or SearchBox widget.
pac-icon The icon displayed to the left of each particular in the list of predictions.
pac-item An item in the list of predictions supplied past the Autocomplete or SearchBox widget.
pac-item:hover The item when the user hovers their mouse pointer over it.
pac-item-selected The item when the user selects it via the keyboard. Notation: Selected items volition be a fellow member of this class and of the pac-item form.
pac-item-query A bridge within a pac-item that is the main role of the prediction. For geographic locations, this contains a place name, similar 'Sydney', or a street name and number, like '10 Rex Street'. For text-based searches such equally 'pizza in New York', it contains the full text of the query. By default, the pac-item-query is colored blackness. If at that place is any additional text in the pac-particular, it is exterior pac-item-query and inherits its styling from pac-item. Information technology is colored gray past default. The additional text is typically an accost.
pac-matched The function of the returned prediction that matches the user'southward input. By default, this matched text is highlighted in bold text. Note that the matched text may be anywhere within pac-item. Information technology is not necessarily part of pac-detail-query, and it could be partly within pac-item-query equally well as partly in the remaining text in pac-detail.

Place Autocomplete optimization

This section describes all-time practices to assistance you brand the most of the Place Autocomplete service.

Here are some general guidelines:

  • The quickest fashion to develop a working user interface is to utilize the Maps JavaScript API Autocomplete widget, Places SDK for Android Autocomplete widget, or Places SDK for iOS Autocomplete UI command
  • Develop an understanding of essential Place Autocomplete information fields from the start.
  • Location biasing and location brake fields are optional simply can have a significant touch on autocomplete performance.
  • Use error handling to make sure your app degrades gracefully if the API returns an fault.
  • Brand sure your app handles when there is no selection and offers users a fashion to go on.

Toll optimization all-time practices

Basic cost optimization

To optimize the cost of using the Place Autocomplete service, utilise field masks in Place Details and Place Autocomplete widgets to return merely the identify data fields you demand.

Advanced cost optimization

Consider programmatic implementation of Identify Autocomplete in order to access Per Request pricing and request Geocoding API results about the selected place instead of Place Details. Per Asking pricing paired with Geocoding API is more cost-effective than Per Session (session-based) pricing if both of the following conditions are met:

  • If you only need the latitude/longitude or address of the user'southward selected place, the Geocoding API delivers this data for less than a Place Details call.
  • If users select an autocomplete prediction within an average of iv Autocomplete predictions requests or fewer, Per Request pricing may be more than price-effective than Per Session pricing.

For help selecting the Place Autocomplete implementation that fits your needs, select the tab that corresponds to your answer to the following question.

Does your application crave any information other than the address and latitude/longitude of the selected prediction?

Yes, needs more details

Employ session-based Place Autocomplete with Place Details.
Since your application requires Identify Details such as the place proper name, business organization status, or opening hours, your implementation of Place Autocomplete should use a session token (programmatically or built into the JavaScript, Android, or iOS widgets) for a total cost of $0.017 per session plus applicable Places Data SKUs depending on which place data fields yous asking.1

Widget implementation
Session management is automatically congenital into the JavaScript, Android, or iOS widgets. This includes both the Place Autocomplete requests and the Place Details asking on the selected prediction. Be sure to specify the fields parameter in order to ensure you are merely requesting the place data fields you demand.

Programmatic implementation
Use a session token with your Place Autocomplete requests. When requesting Place Details about the selected prediction, include the following parameters:

  1. The place ID from the Place Autocomplete response
  2. The session token used in the Place Autocomplete asking
  3. The fields parameter specifying the place information fields you need

No, needs only address and location

Geocoding API could be a more toll-effective option than Place Details for your application, depending on the performance of your Place Autocomplete usage. Every awarding's Autocomplete efficiency varies depending on what users are inbound, where the application is beingness used, and whether operation optimization best practices have been implemented.

In social club to answer the following question, analyze how many characters a user types on boilerplate before selecting a Place Autocomplete prediction in your awarding.

Do your users select a Place Autocomplete prediction in 4 or fewer requests, on average?

Yes

Implement Place Autocomplete programmatically without session tokens and call Geocoding API on the selected identify prediction.
Geocoding API delivers addresses and latitude/longitude coordinates for $0.005 per request. Making four Place Autocomplete - Per Asking requests costs $0.01132 so the full cost of four requests plus a Geocoding API call near the selected place prediction would be $0.01632 which is less than the Per Session Autocomplete price of $0.017 per session.1

Consider employing performance all-time practices to aid your users get the prediction they're looking for in fifty-fifty fewer characters.

No

Apply session-based Identify Autocomplete with Place Details.
Since the average number of requests you expect to make before a user selects a Place Autocomplete prediction exceeds the cost of Per Session pricing, your implementation of Identify Autocomplete should apply a session token for both the Place Autocomplete requests and the associated Place Details asking for a total cost of $0.017 per session.i

Widget implementation
Session management is automatically built into the JavaScript, Android, or iOS widgets. This includes both the Place Autocomplete requests and the Place Details asking on the selected prediction. Be sure to specify the fields parameter in order to ensure you are only requesting Basic Information fields.

Programmatic implementation
Utilise a session token with your Place Autocomplete requests. When requesting Identify Details about the selected prediction, include the following parameters:

  1. The identify ID from the Identify Autocomplete response
  2. The session token used in the Place Autocomplete asking
  3. The fields parameter specifying Basic Data fields such as address and geometry

Consider delaying Place Autocomplete requests
You tin can employ strategies such as delaying a Place Autocomplete request until the user has typed in the commencement three or four characters so that your awarding makes fewer requests. For example, making Identify Autocomplete requests for each graphic symbol later the user has typed the third graphic symbol means that if the user types seven characters then selects a prediction for which you brand one Geocoding API request, the total cost would exist $0.01632 (4 * $0.00283 Autocomplete Per Request + $0.005 Geocoding).1

If delaying requests can get your boilerplate programmatic request beneath four, you can follow the guidance for performant Identify Autocomplete with Geocoding API implementation. Note that delaying requests can be perceived as latency by the user who might be expecting to see predictions with every new keystroke.

Consider employing performance best practices to aid your users get the prediction they're looking for in fewer characters.

Functioning best practices

The following guidelines draw means to optimize Place Autocomplete performance:

  • Add together land restrictions, location biasing, and (for programmatic implementations) language preference to your Place Autocomplete implementation. Language preference is not needed with widgets since they pick language preferences from the user's browser or mobile device.
  • If Place Autocomplete is accompanied by a map, y'all tin can bias location by map viewport.
  • In situations when a user does non choose one of the Autocomplete predictions, mostly because none of those predictions are the desired event-address, you can re-utilise the original user input to endeavour to get more relevant results:
    • If yous wait the user to enter only address data, re-use the original user input in a call to the Geocoding API.
    • If you wait the user to enter queries for a specific identify past proper name or address, use a Observe Place request. If results are merely expected in a specific region, utilise location biasing.
    Other scenarios when it'south best to fall back to the Geocoding API include:
    • Users inputting subpremise addresses in countries other than Australia, New Zealand, or Canada. For example, the Usa address "123 Bowdoin St #456, Boston MA, USA" is not supported by Autocomplete. (Autocomplete supports subpremise addresses only in Australia, New Zealand, and Canada. Supported address formats in these three countries include "ix/321 Pitt Street, Sydney, New S Wales, Commonwealth of australia" or "14/19 Langana Avenue, Browns Bay, Auckland, New Zealand" or "145-112 Renfrew Dr, Markham, Ontario, Canada".)
    • Users inputting addresses with road-segment prefixes like "23-thirty 29th St, Queens" in New York City or "47-380 Kamehameha Hwy, Kaneohe" on the isle of Kauai in Hawai'i.

Usage limits and policies

Quotas

For quota and pricing information, see the Usage and Billing documentation for the Places API.

Policies

Employ of the Places Library, Maps JavaScript API must exist in accord with the policies described for the Places API.

From our Terms of Service

Brandish the required
logos and attributions

Respect Google's copyrights and attribution. Ensure that the logo and copyright notice are visible, and display the "powered by Google" logo if yous're using information without a map.

Larn More than

weaverdirld1936.blogspot.com

Source: https://developers.google.com/maps/documentation/javascript/places-autocomplete

0 Response to "Ionic Google Autocomplete Uncaught Typeerror: Cannot Read Property 'foreach' of Null"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel