在Ionic 或者 Angular 中用 Google Map API 实现自动补全地址(autocomplete)

先上效果图:

Mar-27-2019 12-43-22.gif

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

实现步骤:

环境安装就不提了,无非就是用npm全局安装Ionic 或者 Angular。本文是以Ionic为例。javascript

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.htmlcss

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

我这里直接用homehtml

home.page.ts

home.page.html

4. 运行查看效果

Mar-27-2019 12-43-22.gif

几个注意事项

1. 若是你是Angular6或者以上的版本,请必定要在相关ts文件里的第一行声明这个java

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

若是不是,请声明这一句代码git

import {} from "googlemaps";

具体讨论请看这里:
https://stackoverflow.com/questions/51084724/types-googlemaps-index-d-ts-is-not-a-modulegithub


2. 我这里用的是<ion-input></ion-input>标签,而这个API支持的是原生的HTML<input />标签。若是不是原生的话,会报这个错误:npm

error.png

因此个人在home.page.ts文件里的getPlaceAutocomplete()获取DOM的代码是这样写的api

let ele = document.getElementById('addresstext').getElementsByTagName('input')[0];
若是是原生<input />标签,还能够这样写:

(详细代码请参考github地址)app

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 :)

原生标签.gif

非原生标签.gif


3*.虽然是在ngAfterViewInit()里调用的googleMap初始化函数,理论上此时视图已经初始化好了,因此DOM应该渲染出来了。但实际项目中,仍是会以下所示的错误
error.png
猜测缘由,应该一开始google找不到相关的DOM的节点,因此我在这里加了一个setTimeout()

ngAfterViewInit() {
  setTimeout(() => {
    this.getPlaceAutocomplete();
  },1000);
}
相关文章
相关标签/搜索