我想在我的 Angular Web 应用程序中使用 google map api 但我有这个错误 -> ERROR ReferenceError: google is not defined
我按照原始 google 文档中的所有内容进行操作,但不幸的是它不起作用: https://developers.google.com/maps/documentation/javascript/examples/map-simple
我的 TS 班
/// <reference types="google.maps" />
import { Component } from '@angular/core';
import {} from 'google.maps';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'testapp';
constructor() { }
ngOnInit() {
initMap();
}
}
let map: google.maps.Map;
function initMap(): void {
map = new google.maps.Map(document.getElementById("map") as HTMLElement, {
center: { lat: -34.397, lng: 150.644 },
zoom: 8,
});
}
我的html类
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="./index.js"></script>
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=MyAPIKEY&callback=initMap&libraries=&v=weekly"
async
></script>
</body>
</html>
答案 0 :(得分:0)
您的 index.js 在 Google 地图 API 可用之前被解析。两个选项:
import {Loader} from "@googlemaps/js-api-loader";
// ... removed
constructor() { }
ngOnInit() {
const loader = Loader({apiKey: ''}).load().then(initMap);
}
}
或者,删除异步/回调并将 Google 地图脚本放在 index.js 之上。 (此块直到资源加载完毕。)
<script src="https://maps.googleapis.com/maps/api/js?key=MyAPIKEY&v=weekly"></script>
<script src="./index.js"></script>
...