我已经看到这个问题被问了 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 已加载。如果您查看脚本加载的顺序,map
在 overlay
之前加载;这可能就是您遇到 overlay
而不是 map
问题的原因。但是我认为 map
仍然有问题,这取决于网络速度。
您应该尝试不使用 async
和 defer
加载脚本,以确保在您尝试使用库之前同步加载它
甚至谷歌都建议在尝试对 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/