[英]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.