【问题标题】:Angular - Google is not defined?Angular - Google 没有定义?
【发布时间】:2018-04-22 06:33:38
【问题描述】:

您好,我正在尝试在 angular 中实现 google maps apiangularjs 非常简单,但我不知道什么不起作用。我有一个简单的应用程序,它显示产品及其位置。单击位置后,该位置确实显示在地图上。但是要购买地图,我使用的是google maps。我已经做了很多。但是这个错误不断出现。

google is not defined

app.component.ts

    import { Component } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ProductService } from './product.service';
declare var google: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [ProductService]
})
export class AppComponent {

  //define an array of products
  products = [];

  //constructor func
  constructor(private _productService: ProductService) { }

  //after constructor func this func runs , in which we are
  // accessing the class function getproducts and objects products
  // through this.
  // => means callback in which we are dumping data in products
  //array
  ngOnInit() {
    this._productService.getProducts()
      .subscribe(products => { this.products = products[0].data; console.log(this.products); })

    var map;
    map = new google.maps.Map(document.getElementById('map'), {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8
    });

  }

}

Index.html

    <!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Shopober</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
  <app-root></app-root>
  <script src="https://maps.googleapis.com/maps/api/js?key=xxxxx" async defer>


  </script>
</body>

</html>

app.component.html

 <table id="products">
    <tr>
      <th>Id</th>
      <th>Product Name</th>
      <th>Price</th>
      <th>In Stock</th>
      <th>Location</th>
      <th>Image</th>
    </tr>
    <tr *ngFor="let product of products">
      <td>{{product.id}}</td>
      <td>{{product.product_name}}</td>
      <td>{{product.product_price}}</td>
      <td>{{product.product_stock}}</td>
      <td>
        <a>{{product.location[0].lat + ',' + product.location[0].lng}}</a>
      </td>
      <td>{{product.product_image}}</td>
    </tr>
  </table>

【问题讨论】:

    标签: javascript angular google-maps


    【解决方案1】:

    在加载谷歌地图脚本之前,您必须等待视图初始化。你可以用AfterViewInit 钩子来做,像这样:

    import {AfterViewInit, Component} from '@angular/core';
    ...
    export class YourComponent implements AfterViewInit {
    
      ngAfterViewInit(): void {
        // Load google maps script after view init
        const DSLScript = document.createElement('script');
        DSLScript.src = 'https://maps.googleapis.com/maps/api/js?key=xxxxx'; // replace by your API key
        DSLScript.type = 'text/javascript';
        document.body.appendChild(DSLScript);
        document.body.removeChild(DSLScript);
      }
    

    【讨论】:

    • 你想让我做另一个ts文件并写这段代码吗?或者我可以在我的 app.comp.ts 中执行此操作
    • 添加到包含谷歌地图代码的组件中!
    • 找不到名称“AfterViewInit”。
    • 同样的错误。我做了类似这个导出类 Appcomponent 实现 AfterViewInit { products = []; constructor(private _productService: ProductService) { } ...... 你的代码 }
    • 是的,这是谷歌地图的正常行为,你必须设置一个固定的像素高度,或者调整容器的大小。检查此线程:stackoverflow.com/questions/10209704/…
    【解决方案2】:

    删除 asyncdefer 属性对我有用,但不确定是否应该牢记网站的性能方面。

    所以你的脚本标签应该是这样的:

    &lt;script src="https://maps.googleapis.com/maps/api/js?key=xxxxx"&gt;

    【讨论】:

      【解决方案3】:

      尝试实施 -

      import GoogleMaps from 'google-maps';
      

      导入谷歌地图后使用以下代码:

      GoogleMaps.KEY = <your map api key>;
      GoogleMaps.load((google) => {
        // place your code here
      });
      

      【讨论】:

      • 不想使用任何插件。请解释原始地图api
      【解决方案4】:

      看起来您的组件在 google 脚本之前加载。谷歌地图有一个很棒的 angular2+ 插件:https://github.com/SebastianM/angular-google-maps

      你检查了吗?它允许您使用谷歌地图做所有常见的事情,并避免常见的加载和其他错误。

      【讨论】:

      • 我知道这个插件,但我不想用它
      • 我不确定在没有额外解释的情况下建议插件是否是一个好的回答习惯。
      • 是的,你可能是真的。我会补充一些细节,对不起!
      • 不是一个很棒的插件——在我看来。我遇到了许多错误。而是使用现在内置于 Angular 中的“google-map”。
      【解决方案5】:

      其他方式类似@Boulboulouboule 解决方案

      import {AfterViewInit, Component} from '@angular/core';
      ...
      export class YourComponent implements AfterViewInit {
      
        constructor(private httpClient: HttpClient) {}
      
        ngAfterViewInit(): void {
          this.httpClient.jsonp('https://maps.googleapis.com/maps/api/js?key=xxxxx', 
            'callback')
            .pipe(
               map(() => true),
               catchError(() => of(false)),
            );
          }
      
      }
      

      【讨论】:

        【解决方案6】:

        尝试将初始化封装在 setTimeout() 函数中,如下所示:

        ngOnInit(){
         setTimeout(()=> {
         // Put the logic here 
        
        
         }, 1000);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-10-27
          • 2017-06-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-08-10
          • 1970-01-01
          相关资源
          最近更新 更多