gpt4 book ai didi

ajax - Google Maps API 仅在使用 AJAX 时抛出 "Uncaught ReferenceError: google is not defined"

转载 作者:行者123 更新时间:2023-12-01 19:31:08 24 4
gpt4 key购买 nike

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

Uncaught ReferenceError: google is not defined

这是为什么?

这是带有 map 的页面:

<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>

感谢您的帮助。

最佳答案

文档加载完成后默认无法加载API,需要异步加载。

用 map 修改页面:

<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>

有关更多详细信息,请查看:https://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function/14185834#14185834

示例:http://jsfiddle.net/doktormolle/zJ5em/

关于ajax - Google Maps API 仅在使用 AJAX 时抛出 "Uncaught ReferenceError: google is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14229695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com