Angular - Google map API - 未捕获的 ReferenceError : google is not defined - only sometimes?

标签 angular google-maps typescript

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

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

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

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

@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>

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

最佳答案

这可能是因为叠加层尚未加载,但 map 已加载。如果您查看脚本加载的顺序,mapoverlay 之前加载;这可能就是您遇到 overlay 而不是 map 问题的原因。但是我认为 map 仍然有问题,这取决于网络速度。

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

甚至谷歌都建议在尝试对 API 类进行子类化时同步加载他们的脚本

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

In effect, this will subclass the overlay class therefore it's simpler to load the API synchronously

关于Angular - Google map API - 未捕获的 ReferenceError : google is not defined - only sometimes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459309/

相关文章:

javascript - Angular 2 着陆页

android - 获取两个位置的距离

javascript - 自定义 Google Map API V3 PEGMAN 按钮

angular - 在 Angular 应用程序中使用 graphql-codegen 时出现错误 "Object is of type unknown"

javascript - 分配属性时,如何避免 Microsoft Bot Framework State PropertyAccessor 中出现 Typescript 错误 TS2345

javascript - ReplaySubject(1) 和 AsyncSubject() 一样吗?

angular - Electron + Angular 2 + 节点串行端口

angular - 样式未在新窗口中加载

json - 来自同一用户的数组周围的 Angular6 Div

angularjs - ionic 2 服务命令错误 : Uncaught (in promise): [object PositionError]