我尝试在我的索引页面中加载一个java脚本谷歌地图v3,并加载ajax:
我知道有很多同样的问题,但我不能低估他们。
索引.php
<!DOCTYPE html>
<html>
<head>
<script src="js/vendor/jquery.min.js"></script>
<style type="text/css">
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; }
</style>
</head>
<body>
<div id="mapc"></div>
<span id="btn">load map</span>
<script type="text/javascript">
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
$(document).ready(function(){
$("#btn").click(function(){
$("#mapc").load("map.php");
initMap();
});
});
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
</body>
</html>
注意:我需要谷歌API链接在索引中.php因为我计划在索引中也有谷歌地图.php。
这也是地图.php
<div id="map"></div>
同样在控制台中,我只收到此错误:
js?callback=initMap:74 Uncaught TypeError: Cannot read property 'offsetWidth' of null_.Af @ js?callback=initMap:74_.hg @ js?callback=initMap:81initMap @ (index):19(anonymous function) @ js?callback=initMap:87(anonymous function) @ js?callback=initMap:49_.ac @ js?callback=initMap:46oc @ js?callback=initMap:49(anonymous function) @ js?callback=initMap:123google.maps.Load @ js?callback=initMap:21(anonymous function) @ js?callback=initMap:122(anonymous function) @ js?callback=initMap:123
js?callback=initMap:74 Uncaught TypeError: Cannot read property 'offsetWidth' of null_.Af @ js?callback=initMap:74_.hg @ js?callback=initMap:81initMap @ (index):19(anonymous function) @ (index):28n.event.dispatch @ jquery.min.js:3r.handle @ jquery.min.js:3
您的问题是元素 (( 在页面加载时不存在。单击"#btn"后添加第一个。
点击后首先工作,请参阅:
$(document).ready(function(){
$("#btn").click(function(){
$("#mapc").append('<div id="map"></div>');
initMap();
});
});
html, body { height: 100%; margin: 0; padding: 0; }
#map { height: 100%; width: 500px;
height: 500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<div id="mapc"></div>
<button id="btn">load map</button>
<script async defer
src="https://maps.googleapis.com/maps/api/js">
</script>
只需删除"?callback=initMap"参数,它就可以正常工作,没有错误。
您需要在加载地图.php之后执行initMap();
。
因此,您需要使用 2 个参数调用 load
函数:
- 网址。
- 回调函数。
jQuery Docs
回调函数
如果提供了"完整"回调,则在后处理并执行 HTML 插入后执行。对于 jQuery 集合中的每个元素,回调都会触发一次,然后依次设置为每个 DOM 元素。
在回调函数中,您可以确定映射.php已加载并且 #map
div 存在于 DOM 中。
$("#mapc").load("map.php", function() {
initMap();
});
此外,从 URL 中删除?callback=initMap