2016-12-06 1 views
0

Google지도를 자동으로 작성하여 이온 2 프로젝트에 추가하여 사용자 위치를 업데이트하려고했습니다. 그러나 addEventListener가 작동하지 않는 것으로 보이며 콘솔 오류가 발생할 수 있습니다. 아무도 내가 잘못 가고 있다고 말해?Google지도 장소 자동 완성 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>
구성 요소 아래로 autoCompleteplace_changed 이벤트를 확인하여

답변

1
구글 맵 이벤트는 각 영역 밖에서 발사하기 때문에 당신은 변화를 감지 할 수 thisChangeDetectionRef을 유지하기 위해 화살표 기능을 사용할 수 있습니다

:

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

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(); 반환 당신이 주소를 얻을 수 있도록 다음과 같이 객체

Plunker Example

+0

드롭 다운 프로그램을 입력하지 않고도 시도했지만 console.log ('place_changed', this.location.loc)는 입력 된 값을 인쇄합니다. – Idlliofrio

+0

'function() {'을'() =>'으로 변경 했습니까? – yurzui

+0

예 화살표 기능으로 바 꾸었습니다. – Idlliofrio

0

시도 :

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

관련 문제