【问题标题】:JavaScript - Uncaught ReferenceError: google is not defined? [duplicate]JavaScript - 未捕获的 ReferenceError:未定义谷歌? [复制]
【发布时间】:2018-08-17 12:43:05
【问题描述】:

我从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();

错误截图:

谢谢

【问题讨论】:

  • 打开网络选项卡时,脚本请求是否返回请求的js文件?

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


【解决方案1】:

您的谷歌script 标签上的async defer 正在使谷歌脚本异步加载(非即时)。

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

删除async defer 将正常加载谷歌脚本,在你之前,所以你可以确定它是可用的。

【讨论】:

  • @Tobig 即使删除了async defer,我仍然会遇到同样的错误?
  • 我很确定这是一个不同的错误。我在测试删除async defer 后注意到了这个错误。这必须是一个新问题。
  • @BShaps 我收到 API KEY 错误的事实证明异步问题已修复,并且脚本实际上正在加载...
  • 我有并且仍然有同样的错误,我在问题中添加了一个屏幕截图,它显示了我得到错误的确切位置。
  • ...或者您将async defer留在脚本标签上并使用回调方法:<script src="...googleapi?callback=initMap"></script> - developers.google.com/maps/documentation/javascript/tutorial
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-02
  • 2017-07-09
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 2012-08-28
相关资源
最近更新 更多