2016-12-06 105 views
0

我一直试图添加谷歌地图自动完成在离子2项目更新用户的位置。但是,addEventListener似乎不工作,并没有控制台错误可以有谁告诉我我要去哪里?谷歌地图的地方自动完成addEventListener不工作

ngAfterViewInit() { 
 
    let input = <HTMLInputElement> document.getElementById("auto"); 
 
    console.log('input', input); 
 
    let options = { 
 
    componentRestrictions: { 
 
     country: 'IN', 
 
     types: ['(regions)'] 
 
    } 
 
    } 
 
    let autoComplete = new google.maps.places.Autocomplete(input, options); 
 
    console.log('auto', autoComplete); 
 
    google.maps.event.addListener(autoComplete, 'place_changed', function() { 
 
    this.location.loc = autoComplete.getPlace(); 
 
    console.log('place_changed', this.location.loc); 
 
    }); 
 
}
<ion-label stacked>Search Location</ion-label> 
 
<input type="text" id="auto" placeholder="Enter Search Location" [(ngModel)]="location.loc" />

的index.html

<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxx&libraries=places"></script>

回答

1

您可以使用箭头功能保留thisChangeDetectionRef检测的变化,因为谷歌地图事件角度带外线发炮:

constructor(private cd: ChangeDetectorRef) { } 

google.maps.event.addListener(autoComplete, 'place_changed',() => { // arrow function 
    this.location.loc = autoComplete.getPlace(); 
    this.cd.detectChanges(); // detect changes 
    console.log('place_changed', this.location.loc); 
}); 

autoComplete.getPlace();回报对象,这样你就可以得到地址如下:

var place = autoComplete.getPlace(); 
this.location.loc = place.formatted_address; 

Plunker Example

+0

我尝试过,但仍然保持原样,但输入时没有显示下拉列表,但当我点击输入console.log('place_changed',this.location.loc)打印输入的值 – Idlliofrio

+0

您是否将'function(){'更改为'()=>'? – yurzui

+0

是的,我改变了它的箭头功能 – Idlliofrio

0

尝试通过以下部件检查上autoCompleteplace_changed事件与:

import {Component, ViewChild, ChangeDetectorRef} from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div>  
     <input #auto /> 
     {{ location?.formatted_address | json}} 
    </div> 
    `, 
}) 
export class App { 
    @ViewChild('auto') auto:any; 

    location: any; 

    constructor(private ref: ChangeDetectorRef) { 
    } 

    ngAfterViewInit(){ 
    let options = { 
     componentRestrictions: { 
     country: 'IN' 
     } 
    }; 
    let autoComplete = new google.maps.places.Autocomplete(this.auto.nativeElement, options); 

    console.log('auto', autoComplete); 

    autoComplete.addListener('place_changed',() => { 
     this.location = autoComplete.getPlace(); 
     console.log('place_changed', this.location); 
     this.ref.detectChanges(); 
    }); 
    } 
} 

由于place_changed是在角度js以外触发的,我们需要手动触发角度变化检测ChangeDetectorRef

+0

是的,我试过,但下拉不显示,并没有控制台错误 – Idlliofrio

+0

我已更新我的答案,请检查一次 – ranakrunal9

+0

您可以检查https://plnkr.co/edit/D7pj3tHjR1ElPE1VZZII?p=preview – ranakrunal9

相关问题