[英]load a new google map in current page with load ajax
我尝试使用ajax加载在索引页面中加载Java脚本Google Map v3:
我知道这里有很多相同的问题,但是我不能低估他们。
index.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>
注意:我需要google API链接位于index.php中,因为我也计划在index.php中包含另一个google map。
这也是map.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
您的问题是页面加载时不存在Element()。 单击“ #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”参数,它就可以正常工作,没有错误。
您需要执行initMap();
就在加载map.php 之后 。
因此,您需要使用2个参数调用load
函数:
jQuery文档
回调功能
如果提供了“完成”回调,则在后处理和HTML插入完成后执行该回调。 jQuery集合中的每个元素都会触发一次回调,并将其依次设置为每个DOM元素。
在回调函数中,你可以肯定的是,map.php加载和#map
在DOM DIV存在。
$("#mapc").load("map.php", function() {
initMap();
});
此外,从网址中删除?callback=initMap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.