JavaScript-未捕获的ReferenceError:未定义google吗?

Mr *_*ody 0 javascript google-maps google-maps-api-3

我从这个问题中复制了代码,试图获得两点的指导。显示点的标记和方向。但是,我在控制台中遇到一个错误,Uncaught ReferenceError: google is not defined只是想知道如何摆脱它。

以下是我从上述链接问题的公认答案中获得的JavaScript代码。

function initMap() {
    var pointA = new google.maps.LatLng(51.7519, -1.2578),
        pointB = new google.maps.LatLng(50.8429, -0.1313),
        myOptions = {
            zoom: 7,
            center: pointA
        },
        map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
        // Instantiate a directions service.
        directionsService = new google.maps.DirectionsService,
        directionsDisplay = new google.maps.DirectionsRenderer({
            map: map
        }),
        markerA = new google.maps.Marker({
            position: pointA,
            title: "point A",
            label: "A",
            map: map
        }),
        markerB = new google.maps.Marker({
            position: pointB,
            title: "point B",
            label: "B",
            map: map
        });

    // get route from A to B
    calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB);

}

function calculateAndDisplayRoute(directionsService, directionsDisplay, pointA, pointB) {
    directionsService.route({
        origin: pointA,
        destination: pointB,
        travelMode: google.maps.TravelMode.DRIVING
    }, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        } else {
            window.alert('Directions request failed due to ' + status);
        }
    });
}

initMap();
Run Code Online (Sandbox Code Playgroud)

错误屏幕截图:

在此处输入图片说明 谢谢

Tob*_*biq 6

async defer,在你的谷歌script标签,正在谷歌的脚本加载进行异步(非即时)。

当脚本正在加载并立即执行时。因此,您的脚本甚至在将Google api加载到文档之前都引用了它。

删除async defer通常会先加载Google脚本,然后再加载,因此您可以确定该脚本将可用。