首页 文章

加载Google地方信息自动填充Async Angular 2

提问于
浏览
3

我试图在Angular 2组件中实例化Google Places Autocomplete输入 . 我用这段代码来做:

loadGoogle() {
    let autocomplete = new google.maps.places.Autocomplete((this.ref.nativeElement), { types: ['geocode'] });
    let that = this
    //add event listener to google autocomplete and capture address input
    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      let place = autocomplete.getPlace();
      that.place = place;
      that.placesearch = jQuery('#pac-input').val();
    });
    autocomplete.addListener()
  }

通常,我相信,我会使用Google API提供的回调函数来确保在此函数运行之前加载它,但我无法在组件的范围内访问它 . 我能够在90%的时间内加载自动完成输入,但在较慢的连接上,我有时会出错

google is not defined

有没有人想过如何确保在实例化之前在组件中加载Google API .

2 回答

  • 4

    我使用它与上面解释的相同,但根据谷歌页面速度我得到这个建议,

    删除渲染阻止JavaScript:http://maps.googleapis.com/ ... es = geometry,places&region = IN&language = en

    所以我改变了我的实施,

    <body>
      <app-root></app-root>
      <script src="http://maps.googleapis.com/maps/api/js?client=xxxxx2&libraries=geometry,places&region=IN&language=en" async></script>
    </body>
    

    / *现在在我的component.ts * /

    triggerGoogleBasedFn(){
        let _this = this;
    
        let interval = setInterval(() => {
          if(window['google']){
            _this.getPlaces();
            clearInterval(interval);
          }
        },300)
      }
    

    您可以再做一件事,一旦收到 Value (谷歌)就发出事件,并在其中触发您的谷歌任务 .

  • 0

    不确定这是否有帮助,但我只是在index.html中使用一个简单的脚本标记来加载Google API,我从来没有收到任何错误 . 我相信你做的也一样 . 我在这里发布我的代码,希望它有所帮助 .

    注意:我使用Webpack加载除Google Map API之外的其他脚本 .

    <html>
      <head>
        <base href="/">
        <title>Let's Go Holiday</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Google Map -->
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<your-key>&libraries=places"></script>
      </head>
    
      <body>
        <my-app>Loading...</my-app>
      </body>
    </html>
    

    然后在你的组件中:

    ...
    declare var google: any;
    
    export class SearchBoxComponent implements OnInit {
    
      ngOnInit() {
        // Initialize the search box and autocomplete
        let searchBox: any = document.getElementById('search-box');
        let options = {
          types: [
            // return only geocoding results, rather than business results.
            'geocode',
          ],
          componentRestrictions: { country: 'my' }
        };
        var autocomplete = new google.maps.places.Autocomplete(searchBox, options);
    
        // Add listener to the place changed event
        autocomplete.addListener('place_changed', () => {
          let place = autocomplete.getPlace();
          let lat = place.geometry.location.lat();
          let lng = place.geometry.location.lng();
          let address = place.formatted_address;
          this.placeChanged(lat, lng, address);
        });
      }
      ...
    }
    

相关问题