如何在 Angular 中存储来自谷歌位置自动完成的纬度和经度

dev*_*ato 2 google-maps google-maps-api-3 angular

自从一年前我遵循本教程以来,我决定在 stackoverflow 中发布问题和答案:https ://www.youtube.com/watch?v=pxyX_5mtlTk 。我试图从 Angular 中的谷歌位置自动完成中检索纬度和经度。我试图用谷歌搜索解决方案,在这里发布问题(没有人回答,所以我删除了我的问题),但我没有运气,最终我能够弄清楚,我决定在 YouTube 教程上发布我知道如何去做吧,从一年前开始,我收到了 35 封电子邮件询问我的解决方案,所以我决定也在这里分享。

dev*_*ato 5

问题是 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)
  }
Run Code Online (Sandbox Code Playgroud)

在你的html中

<input [hidden]="!isLoggedIn()" class="albergueInfo" type="text" autocorrect="off" autocapitalized="off" 
      spellcheck="off"
      placeholder=""
      #address [value]="addressValue" (input)="addressValue=$event.target.value"/>
Run Code Online (Sandbox Code Playgroud)

您还可以检索不仅仅是纬度和经度的更多信息 。按照 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;
  }
Run Code Online (Sandbox Code Playgroud)