Tìm một cách thực tế.
Fiddle ở đây với sự kiện tùy chỉnh (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();
})());
EDIT Chức năng loadGoogleMaps
có thể là thực tế hơn nếu khai báo trong phạm vi toàn cầu, đặc biệt là khi làm việc trong một ứng dụng ajax. Và một kiểm tra boolean sẽ ngăn tải api nhiều lần vì điều hướng.
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();
});
Nguồn
2012-09-26 13:27:07
Tôi đã chỉnh sửa mã và thêm mã mẫu. Vui lòng xem lại. –
nếu bạn không cần nó trong SPA sau thì sao? Tại sao người dùng phải chờ tập lệnh tải? – SuperUberDuper