First on the renderings:

Github: https://github.com/luchenwei9…

Implementation steps:

Ionic or Angular is installed globally using NPM, regardless of the environment. Ionic is used as an example in this paper.

1. Installtype/googlemaps
npm install type/googlemaps -save
2. Declare the Google API Key in your applicationindex.htmlIn the

To apply for the address
https://developers.google.com/maps/documentation/javascript/get-api-key

Replace the value at key with your key and place the code in index.html

<script src="https://maps.googleapis.com/maps/api/js?key=your-google-key&libraries=places"></script>
3. Write code

I’m just going to use home

4. Run to see the effect

A few considerations

1. If you are Angular6 or above, be sure to state this in the first line of the relevant TS file

/// <reference types="@types/googlemaps" />

If not, please declare this line of code

import {} from "googlemaps";

Specific discussion here: https://stackoverflow.com/questions/51084724/types-googlemaps-index-d-ts-is-not-a-module


2. I’m using the
tag, whereas the API supports the native HTML tag. If it is not native, this error will be reported:

So my code for getPlaceAutoComplete () fetching the DOM in the home.page.ts file looks like this

let ele = document.getElementById('addresstext').getElementsByTagName('input')[0];
If it’s native<input />Label, you can also write:

(For detailed code, please refer to GitHub address)

The HTML file

<input #addresstext style="border:1px solid #111; width: 100%" />

Ts file

/// <reference types="@types/googlemaps" /> import { Component, ViewChild, OnInit, AfterViewInit , NgZone } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit, AfterViewInit { @ViewChild('addresstext') addresstext: any; . private getPlaceAutocomplete() { let ele = this.addresstext.nativeElement; const autocomplete = new google.maps.places.Autocomplete(ele, { ... }}

The difference is that if it’s native HTML, Google will automatically add placeholder for you 🙂


3*. Although it is inngAfterViewInit()In theory, the view is already initialized, so the DOM should be rendered. However, in the real project, you will still have the following error



For a guess, Google couldn’t find the relevant DOM node at first, so I added one heresetTimeout()

ngAfterViewInit() { setTimeout(() => { this.getPlaceAutocomplete(); }, 1000); }