【问题标题】:Angular - Google maps API - Uncaught ReferenceError: google is not defined - only sometimes?Angular - Google maps API - Uncaught ReferenceError: google is not defined - 只是有时?
【发布时间】:2018-03-24 17:10:33
【问题描述】:

我已经看到这个问题被问了 100 次,但似乎没有一个答案有效。我正在尝试像这样声明一个类:

class Popup extends google.maps.OverlayView {
  // Classy stuff
}

但我总是收到错误Uncaught ReferenceError: google is not defined

问题是,Google 地图在我的代码中的其他任何地方都可以使用,但在我声明此类时却不行。另外,我在这样的课程之后声明它:

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss',]
})
export class MapComponent implements AfterViewInit, OnDestroy {
  map: google.maps.Map; <-- No problem with google namespace here
  // Map stuff
}

class Popup extends google.maps.OverlayView { <-- Problem is with this google namespace
  // Classy stuff
}

我刷新页面,有时它会加载,有时会崩溃并给我这个错误。

我正在像这样加载我的 index.html:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=myKey&libraries=places"></script>

它总是有效(我在整个项目中都使用谷歌地图,并且还没有遇到任何其他谷歌命名空间的问题。就在我尝试创建该类时)

【问题讨论】:

    标签: angular google-maps typescript


    【解决方案1】:

    这可能是因为尚未加载叠加层,但地图已加载。如果查看脚本加载的顺序,map 在 overlay 之前加载;这可能就是您对overlay 有问题但对map 没有问题的原因。但是我认为map 仍然可能存在问题,具体取决于网络速度。

    您应该尝试不使用 async 和 defer 加载脚本,以确保在尝试使用之前同步加载库

    甚至 Google 都建议在尝试子类化 API 类时同步加载他们的脚本

    https://developers.google.com/maps/documentation/javascript/examples/overlay-simple

    实际上,这将继承覆盖类,因此 同步加载 API 更简单

    【讨论】:

      【解决方案2】:

      在四处寻找解决方法之前,您可能需要查看此Angular Google Map API Documentation。

      请随时查看these answers on SO,因为它们似乎解决了您遇到的相同问题。

      可能是:1) 您的脚本未正确加载,因此无法识别全局 Google.Maps。或... 2) angular-google-maps 在 Google Maps SDK 完全准备好之前处理指令。

      【讨论】:

      • 看起来这可能适用于 AngularJs。如果 Angular 有一个像样的,那会很好,但我从来没有找到任何我可以定制得足够好的东西。我确实认为您对未按正确顺序加载的内容是正确的...
      猜你喜欢
      • 1970-01-01
      • 2021-12-09
      • 2015-08-11
      • 2012-12-23
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多