【问题标题】:Getting google not defined errors possibly because of asynchronous load of Google maps API谷歌未定义错误可能是由于谷歌地图 API 的异步加载
【发布时间】:2017-08-17 14:37:42
【问题描述】:

我的 jsp 页面中有两个 Javascript 加载,第一个加载 google maps API,第二个加载调用 google.maps.OverlayView 的 JS 文件。由于 googleapis 的异步加载,对 google 的引用显然失败了,但是即使我删除了 async 和 defer,问题仍然存在。有人可以推荐一种解决方法吗?

<%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=mykey>"> 
</script>

 <!-- This file uses Google APIs --> 
 <script src="<c:url value="/resources/js/InfoBox.js"/>">
 </script>
</head>
<body>
<script> 
//This is the callback function after Google Maps API loads
function initMap() {
    var container=document.getElementById("map");
    var anantapur = {lat: 14.68, lng: 77.6};

    var mapOptions = {
        styles: mapStyle,
        zoom: 6,
        minZoom: 5,
        maxZoom: 10,
        center: anantapur
    };
    var newMap = new google.maps.Map(container, mapOptions);
}
</script>
</body>
</html>

上述内容将导致 InfoBox.js 中使用 google maps 对象的行出现错误“google not defined”。

一般来说,如果我只能异步加载 Google APIs 脚本,如何包含其他使用 Google API 对象的脚本文件?

【问题讨论】:

  • 你不能在第一次加载后在回调中加载第二个文件吗?
  • 请提供一个minimal reproducible example 来证明这个问题。
  • 谢谢。我正是这样做的——我在回调中动态加载了第二个文件并且它起作用了。我是 javascript 新手,不熟悉动态加载,并在 stackflow 中找到了如何做到这一点。

标签: javascript google-maps asynchronous


【解决方案1】:

正如 Chris Hawkes 所建议的,我在回调函数中动态加载了第二个文件并且它工作正常。

<%@ page language="java" contentType="text/html; charset=UTF-8"
      pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?key=mykey>" async defer >
</script>

</head>
<body>
<script>
function loadScript(url)
{
    document.body.appendChild(document.createElement("script")).src = url;
}

//This is the callback function after Google Maps API loads
function initMap() {
    var container=document.getElementById("map");
    var anantapur = {lat: 14.68, lng: 77.6};

    //dynamic load of script file that uses google api objects
    loadScript("<c:url value="/resources/js/InfoBox.js"/>"); 

    var mapOptions = {
        styles: mapStyle,
        zoom: 6,
        minZoom: 5,
        maxZoom: 10,
        center: anantapur
    };
    var newMap = new google.maps.Map(container, mapOptions);
}
</script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    相关资源
    最近更新 更多