JavaScript - Uncaught ReferenceError : google is not defined?

标签 javascript google-maps google-maps-api-3

我从 this question 复制了代码尝试获取两个点的方向。显示该点的标记和方向。但是,我在控制台中收到错误 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();

错误屏幕截图:

enter image description here 谢谢

最佳答案

Google script 标记上的 async defer 使 Google 脚本异步(非即时)加载。

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

删除async defer将在您的脚本之前正常加载Google脚本,因此您可以确保它可用。

关于JavaScript - Uncaught ReferenceError : google is not defined?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185368/

相关文章:

javascript - 谷歌地图自动完成在模式弹出窗口中不起作用

javascript - 无法分配给 true 的只读属性 'x'

java - Android 谷歌地图 "NoClassDefFound"

javascript - 有没有办法始终将 Google map 标记固定在其 map 的中心?

javascript - 谷歌自动完成地方API错误

javascript - node.js 无法在集成测试中上传文件

javascript - Angular 过滤器和 ng-click 不起作用

android - 将纬度和经度值转换为 google map api v2 中的地址

带有谷歌地图经纬度的 MySQL GeomFromText

javascript - 谷歌地图未捕获类型错误: Cannot read property 'start_location' of undefined in google maps