当我尝试使用 ajax 加载谷歌地图 v3 时,结果是:
<script src="http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/8a/main.js" type="text/javascript"></script>
在源代码中,我想用 javascript document.write(); 编写;
没有 iframe 我怎么能做到这一点?
谢谢。
当我尝试使用 ajax 加载谷歌地图 v3 时,结果是:
<script src="http://maps.gstatic.com/intl/en_us/mapfiles/api-3/2/8a/main.js" type="text/javascript"></script>
在源代码中,我想用 javascript document.write(); 编写;
没有 iframe 我怎么能做到这一点?
谢谢。
找到了一个实用的方法。
在这里摆弄自定义事件(jQuery):http : //jsfiddle.net/fZqqW/94/
window.gMapsCallback = function(){
$(window).trigger('gMapsLoaded');
}
$(document).ready((function(){
function initialize(){
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(47.3239, 5.0428),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
function loadGoogleMaps(){
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(window).bind('gMapsLoaded', initialize);
loadGoogleMaps();
})());
编辑loadGoogleMaps
如果在全局范围内声明
该函数可能更实用,尤其是在 ajax 应用程序中工作时。由于导航,布尔检查将阻止多次加载 api。
var gMapsLoaded = false;
window.gMapsCallback = function(){
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
if(gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
$(document).ready(function(){
function initialize(){
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(47.3239, 5.0428),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
}
$(window).bind('gMapsLoaded', initialize);
window.loadGoogleMaps();
});
我已经这样做了......这个例子使用jQuery和谷歌地图v3.x
$.getScript("http://maps.google.com/maps/api/js?sensor=true®ion=nz&async=2&callback=MapApiLoaded", function () {});
function MapApiLoaded() {
//.... put your map setup code here: new google.maps.Map(...) etc
}
您必须在谷歌地图 API 脚本中使用此参数 'callback=initialize' 来加载 ajax:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
这是谷歌地图文档:
简单且有效的解决方案(使用 jQuery):
var gMapsLoaded = false;
function loadGoogleMaps() { if(!gMapsLoaded) { $.getScript("https://maps.googleapis.com/maps/api/js?sensor=false&async=2&callback=GoogleMapsLoaded", function(){}); } else { GoogleMapsLoaded(); } }
function GoogleMapsLoaded() {
gMapsLoaded = true;
// your code here - init map ...
}
将此粘贴到您的脚本中,然后调用函数loadGoogleMaps(); 当你需要的时候!