先上效果图:

Github: https://github.com/luchenwei9266/Ionic-googleMap-autocomplete
实现步骤:
环境安装就不提了,无非就是用npm全局安装Ionic 或者 Angular。本文是以Ionic为例。
1. 安装type/googlemaps
npm install type/googlemaps -save
2. 把Google API Key 声明在你的index.html
里
申请地址 https://developers.google.com/maps/documentation/javascript/get-api-key
在key处的值替换成你的的key,然后将这段代码放到index.html
里
<script src="https://maps.googleapis.com/maps/api/js?key=your-google-key&libraries=places"></script>
3. 编写代码
我这里直接用home
了


4. 运行查看效果

几个注意事项
1. 如果你是Angular6
或者以上的版本,请一定要在相关ts文件里的第一行声明这个
/// <reference types="@types/googlemaps" />
如果不是,请声明这一句代码
import {} from "googlemaps";
具体讨论请看这里:
https://stackoverflow.com/questions/51084724/types-googlemaps-index-d-ts-is-not-a-module
2. 我这里用的是<ion-input></ion-input>
标签,而这个API支持的是原生的HTML<input />
标签。如果不是原生的话,会报这个错误:

所以我的在home.page.ts
文件里的getPlaceAutocomplete()
获取DOM的代码是这样写的
let ele = document.getElementById('addresstext').getElementsByTagName('input')[0];
如果是原生<input />
标签,还可以这样写:
(详细代码请参考github地址)
html文件
<input #addresstext style="border:1px solid #111;width: 100%" />
ts文件
/// <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,
{
...
}
}
顺便放一下两者的效果图,让大家看一下效果图,可以发现区别是,如果是原生的HTML标签,google会自动帮你添加placeholder
:)


3*.虽然是在ngAfterViewInit()
里调用的googleMap初始化函数,理论上此时视图已经初始化好了,所以DOM应该渲染出来了。但实际项目中,还是会如下所示的错误

猜想原因,应该一开始google找不到相关的DOM的节点,所以我在这里加了一个
setTimeout()
ngAfterViewInit() {
setTimeout(() => {
this.getPlaceAutocomplete();
},1000);
}
网友评论