小编典典

仅当使用AJAX时,Google Maps API才会引发“ Uncaught ReferenceError:未定义google”

ajax

我有一个使用Google Maps API来显示地图的页面。当我直接加载页面时,地图出现。但是,当我尝试使用AJAX加载页面时,出现错误:

Uncaught ReferenceError: google is not defined

为什么是这样?

这是带有地图的页面:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}
$(document).ready(function(e) { initialize() });
</script>
<div id="map_canvas" style="height: 354px; width:713px;"></div>

这是带有AJAX调用的页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(e) {
    $('button').click(function(){
        $.ajax({
            type: 'GET', url: 'map-display',
            success: function(d) { $('#a').html(d); }
        })
    });
});
</script>
<button>Call</button>
<div id="a"></div>
</body>
</html>

谢谢你的帮助。


阅读 335

收藏
2020-07-26

共1个答案

小编典典

默认情况下,文档完成加载后无法加载该API,您需要异步加载该API。

用地图修改页面:

<div id="map_canvas" style="height: 354px; width:713px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script>
var directionsDisplay,
    directionsService,
    map;

function initialize() {
  var directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = { zoom:7, mapTypeId: google.maps.MapTypeId.ROADMAP, center: chicago }
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  directionsDisplay.setMap(map);
}

</script>
2020-07-26