自从一年前遵循本教程后,我决定将问题和答案发布在stackoverflow中:https://www.youtube.com/watch?v=pxyX_5mtlTk。我试图从Angular的Google地方自动完成中检索经纬度。我尝试通过Google搜索解决方案,在(没有人回答,所以我删除了我的问题)上发布了问题,但我没有运气,最终我能够弄清楚了,因此决定在youtube教程,我知道该怎么做,自一年前以来,我收到了35封电子邮件,要求我提供解决方案,所以我决定在这里分享。
答案 0 :(得分:4)
问题在于,Google会在自动填充中使用回调,并且当您想存储由api填充的信息时,如果它不在回调内部,则将很难存储它。
在您的ts文件中
autocompleteSearch() {
this.mapsAPILoader.load().then(
() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElement.nativeElement, {types:["address"]});
autocomplete.addListener("place_changed", ()=>{
this.ngZone.run(()=>{
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
if(place.geometry === undefined || place.geometry === null) {
return;
}
this.lat = place.geometry.location.lat();
this.lng = place.geometry.location.lng();
})
})
}
);
console.log(this.lat, this.lng)
}
在您的html中
<input [hidden]="!isLoggedIn()" class="albergueInfo" type="text" autocorrect="off" autocapitalized="off"
spellcheck="off"
placeholder=""
#address [value]="addressValue" (input)="addressValue=$event.target.value"/>
您还可以获取除经纬度以外的更多信息 。按照Google Places api json对象结构(https://developers.google.com/places/web-service/details),您可以执行以下操作:
autocompleteSearch() {
this.mapsAPILoader.load().then(
() => {
let autocomplete = new google.maps.places.Autocomplete(this.addressElement.nativeElement, {types:["address"]});
autocomplete.addListener("place_changed", ()=> {
this.ngZone.run(()=>{
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
if(place.geometry === undefined || place.geometry === null) {
return;
}
this.lat = place.geometry.location.lat();
this.long = place.geometry.location.lng();
this.addressArray = place.address_components;
this.address = place.formatted_address
this.city = this.retriveAddressComponents('locality');
this.country = this.retriveAddressComponents('country');
this.zipcode = this.retriveAddressComponents('postal_code');
this.state = this.retriveAddressComponents('administrative_area_level_1');
})
})
});
}
retriveAddressComponents(type : string) {
let res = this.addressArray.find(address_components => address_components.types[0] === type);
return res.long_name;
}