简体   繁体   English

Google Places 自动完成 + Angular2

[英]Google Places Autocomplete + Angular2

I am building a simple Google Places Autocomplete Angular2 directive but the problem is that cannot get any prediction (the response is always empty?!)...我正在构建一个简单的 Google Places Autocomplete Angular2 指令,但问题是无法获得任何预测(响应始终为空?!)...

As a proof of concept I created the simplest possible code snippet as a reference:作为概念证明,我创建了最简单的代码片段作为参考:

<!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>

The above code works - I can get predictions after clicking Go button.上面的代码有效 - 单击 Go 按钮后我可以获得预测。

Now, Angular2 scenario:现在,Angular2 场景:

My _Layout.cshtml file has the following tag in head section:我的 _Layout.cshtml 文件在 head 部分有以下标记:

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

My directive:我的指令:

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'] });
    }
}

And simple Angular component:和简单的 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>

The Scenario 2 (angular) doesn't work.场景 2(角度)不起作用。 The facts:事实:

  • autocomplete is initialized (it has all expected properties/methods, placeholder is "Enter a location", etc...)自动完成已初始化(它具有所有预期的属性/方法,占位符是“输入位置”等...)
  • autocomplete doesn't return any prediction for typed search string (it returns only "/**/ xdc ._le3zv3 && xdc ._le3zv3( [4] )")自动完成不返回对输入搜索字符串的任何预测(它只返回“/**/ xdc ._le3zv3 && xdc ._le3zv3( [4] )”)

Also, Google API Console says everything is as it should be?!此外,谷歌 API 控制台说一切都应该如此?! Here is the screenshot:这是屏幕截图:

仪表板截图

What can be in question here?这里有什么问题? Thanks...谢谢...

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);
  }
}

To use使用

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

@Habeeb's answer is a great start, but this is a cleaner implementation. @Habeeb 的回答是一个很好的开始,但这是一个更清晰的实现。 First install the googlemaps typings npm install --save-dev @types/googlemaps and import them somewhere in your app import {} from '@types/googlemaps' .首先安装 googlemaps npm install --save-dev @types/googlemaps并将它们import {} from '@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);
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM