Angular Google Places Autocomplete+;角2

Angular Google Places Autocomplete+;角2,angular,google-places-api,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&qu

我正在构建一个简单的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>

去
var autocomplete=null;
函数go(){
autocomplete=new google.maps.places.autocomplete(
(document.getElementById('autocomplete')){
类型:['geocode']
});
}
上面的代码有效-我可以在点击Go按钮后得到预测

现在,Angular2场景:

My_Layout.cshtml文件的标题部分具有以下标记:

<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/core'导入{Directive,ElementRef,Input}; 声明:任何; @指令({选择器:'[googleplaces]'}) 导出类GooglePlacesDirective{ 自动完成:任何; 构造函数(专用el:ElementRef){ } ngAfterContentInit(){ this.autocomplete=new google.maps.places.autocomplete( (此为国家元素), {类型:['geocode','cities']}); } } 和简单的角度分量:

<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(角度)不起作用。事实:

  • 自动完成已初始化(它具有所有预期的属性/方法,占位符为“输入位置”,等等)
  • “自动完成”不会为键入的搜索字符串返回任何预测(它只返回“/**/xdc.\u le3zv3&&xdc.\u le3zv3([4]))
而且,谷歌API控制台说一切都是它应该的?!以下是截图:

这里有什么问题?谢谢…

从“@angular/core”导入{指令,ElementRef,EventEmitter,Output};
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);
  }
}
从'@angular/forms'导入{NgModel}; 声明:任何; @指示({ 选择器:“[Googleplace]”, 提供者:[NgModel], 主持人:{ '(输入)''onInputChange()' } }) 导出类GoogleplaceDirective{ @Output()setAddress:EventEmitter=neweventEmitter(); 模型值:任意; 自动完成:任何; 私有:HTMLElement; 构造函数(el:ElementRef,私有模型:NgModel){ 这一点。_el=el.nativeElement; this.modelValue=this.model; var输入=此值; this.autocomplete=new google.maps.places.autocomplete(输入,{}); google.maps.event.addListener(this.autocomplete,'place\u changed',()=>{ var place=this.autocomplete.getPlace(); 本.调用事件(地点); }); } invokeEvent(位置:Object){ this.setAddress.emit(place); } onInputChange(){ log(this.model); } }
使用

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

@Habeeb的答案是一个很好的开始,但这是一个更干净的实现。首先安装googlemaps typings
npm安装——保存dev@types/googlemaps
,并将它们从“@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);
    });
  }
}
import{Directive,ElementRef,EventEmitter,OnInit,Output}来自“@angular/core”;
@指示({
//xx是你的应用的前缀
选择器:“[xxPlaceLookup]”
})
导出类PlaceLookupDirective实现OnInit{
@Output()onSelect:EventEmitter=neweventemitter();
私有元素:HTMLInputElement;
构造函数(el:ElementRef){
this.element=el.nativeElement;
}
恩戈尼尼特(){
const autocomplete=new google.maps.places.autocomplete(this.element{
类型:[“机构”],
组件限制:{国家:'us'}
});
google.maps.event.addListener(自动完成,'place\u changed',()=>{
const place=autocomplete.getPlace();
this.onSelect.emit(place);
});
}
}

完美!非常感谢@Habeeb!如果你得到了预期的结果。请记为正确答案。嗨,哈比,我是新来的。。我试图在我的页面中添加一个自动完成功能…当我搜索解决方案时,我发现了这篇文章。当“this.autocomplete=new google.maps.places.autocomplete(input,{}”);这一行到达时,我得到了一个类似“InvalidValueError:不是HTMLInputElement的实例”的错误…你能帮我找出这个错误吗?@Girija你在代码中添加了吗?我必须将调用包装到
this.setAddress.emit(place)NgZone.run()
构造函数(私有区域:NgZone,…)
,然后在事件侦听器中的
this.zone.run(()=>{this.setAddress.emit(place);})
。没有它,一些模型到UI视图的同步就不会立即触发Cycleaner实现NgZone.run()
构造函数(私有区域:NgZone,…)
,然后在事件侦听器中的
this.zone.run(()=>{this.setAddress.emit(place);})
。没有它,一些从模型到用户界面的视图同步就不会立即触发。你说的应用程序中的某个地方是什么意思?