Google商家信息自动填充功能+ Angular2

时间:2017-02-20 10:21:03

标签: angular google-places-api

我正在构建一个简单的Google Places Autocomplete Angular2指令,但问题是无法获得任何预测(响应始终为空?!)...

作为概念证明,我创建了最简单的代码片段作为参考:

<!DOCTYPE html>
<html>

<head>
    <script src="https://maps.googleapis.com/maps/api/js?key=[MY_API_KEY]&libraries=places" async defer></script>
</head>

<body>
    <button type="button" onclick="go()">go</button>
    <input id="autocomplete" type="text"></input>
    <script>
    var autocomplete = null;

    function go() {
        autocomplete = new google.maps.places.Autocomplete(
            (document.getElementById('autocomplete')), {
                types: ['geocode']
            });
    }
    </script>
</body>

</html>

以上代码有效 - 点击Go按钮后我可以得到预测。

现在,Angular2场景:

我的_Layout.cshtml文件在head section中有以下标记:

<script src="https://maps.googleapis.com/maps/api/js?key=[MY_API_KEY]&libraries=places" async defer></script>

我的指示:

import { Directive, ElementRef, Input } from '@angular/core';

declare var google: any;

@Directive({ selector: '[googleplaces]' })
export class GooglePlacesDirective {

    autocomplete: any;

    constructor(private el: ElementRef) {

    }

    ngAfterContentInit() {
        this.autocomplete = new google.maps.places.Autocomplete(
            (this.el.nativeElement),
            { types: ['geocode', 'cities'] });
    }
}

简单的Angular组件:

<form [formGroup]="companyForm">

    .
    .
    .

    <div class="form-group">
        <label for="Location">Location</label>
        <input type="text" 
               class="form-control" 
               id="Location" 
               fromControlName="Location" 
               googleplaces>
    </div>
</form>

场景2(角度)不起作用。事实:

  • 初始化自动填充(它具有所有预期的属性/方法,占位符为&#34;输入位置&#34;等等...)
  • 自动填充不会返回对键入的搜索字符串的任何预测(它仅返回&#34; / ** / xdc ._ le3zv3&amp;&amp; xdc ._le3zv3([4])&#34;)

此外,谷歌API控制台说一切都应该是这样的?!这是截图:

enter image description here

这里有什么问题?感谢...

2 个答案:

答案 0 :(得分:12)

import {Directive, ElementRef, EventEmitter, Output} from '@angular/core';
import {NgModel} from '@angular/forms';

declare var google:any;

@Directive({
  selector: '[Googleplace]',
  providers: [NgModel],
  host: {
    '(input)' : 'onInputChange()'
  }
})
export class GoogleplaceDirective {

   @Output() setAddress: EventEmitter<any> = new EventEmitter();
  modelValue:any;
  autocomplete:any;
  private _el:HTMLElement;


  constructor(el: ElementRef,private model:NgModel) {
    this._el = el.nativeElement;
    this.modelValue = this.model;
    var input = this._el;

    this.autocomplete = new google.maps.places.Autocomplete(input, {});
    google.maps.event.addListener(this.autocomplete, 'place_changed', ()=> {
      var place = this.autocomplete.getPlace();
      this.invokeEvent(place);

    });
  }

  invokeEvent(place:Object) {
    this.setAddress.emit(place);
  }

  onInputChange() {
    console.log(this.model);
  }
}

使用

<input type="text" class="form-control" placeholder="Location" name="Location" [(ngModel)]="address" #LocationCtrl="ngModel"
        Googleplace (setAddress)="getAddressOnChange($event,LocationCtrl)">

答案 1 :(得分:8)

@ Habeeb的答案是一个很好的开始,但这是一个更清洁的实现。首先安装googlemaps typings npm install --save-dev @types/googlemaps并将其导入应用import {} from '@types/googlemaps'中的某个位置。

import { Directive, ElementRef, EventEmitter, OnInit, Output } from '@angular/core';

@Directive({
  // xx is your app's prefix
  selector: '[xxPlaceLookup]'
})
export class PlaceLookupDirective implements OnInit {
  @Output() onSelect: EventEmitter<any> = new EventEmitter();

  private element: HTMLInputElement;

  constructor(el: ElementRef) {
    this.element = el.nativeElement;
  }

  ngOnInit() {
    const autocomplete = new google.maps.places.Autocomplete(this.element, {
      types: ['establishment'],
      componentRestrictions: {country: 'us'}
    });
    google.maps.event.addListener(autocomplete, 'place_changed', () => {
      const place = autocomplete.getPlace();
      this.onSelect.emit(place);
    });
  }
}
相关问题