有人使用过Googlemaps V3和require.js之类的东西吗?需要它是AMD版本的吗?已经有人做过这样的事情了吗?
有人使用过Googlemaps V3和require.js之类的东西吗?需要它是AMD版本的吗?已经有人做过这样的事情了吗?
define([
'async!http://maps.google.com/maps/api/js?sensor=false'
], function(){
//Create your map.
});
// gmapsDone.js
window._mapsLoaded = $.Deferred();
window.gmapsLoaded = function(data) {
delete window.gmapsLoaded;
_mapsLoaded.resolve();
};
define(["http://maps.google.com/maps/api/js?v=3&sensor=false&callback=gmapsLoaded"], function(gmaps) {
"use strict";
return window._mapsLoaded.done;
});
define(["gmapsDone"], function(gmapsDone) {
function load() {
// Do something
}
gmapsDone(load);
});
https://gist.github.com/taktran/5389668
受http://blog.pixelingene.com/2011/10/using-jquery-dot-deferred-and-requirejs-to-lazy-load-google-maps-api/启发我最近通过一个 $.Deferred 的方法帮助朋友解决了这个问题。这种方法与优化器兼容,不会引起多次脚本加载。
var google_maps_loaded_def = null;
define(['jquery'],function($) {
if(!google_maps_loaded_def) {
google_maps_loaded_def = $.Deferred();
window.google_maps_loaded = function() {
google_maps_loaded_def.resolve(google.maps);
}
require(['http://maps.googleapis.com/maps/api/js?sensor=true&callback=google_maps_loaded'],function(){},function(err) {
google_maps_loaded_def.reject();
//throw err; // maybe freak out a little?
});
}
return google_maps_loaded_def.promise();
});
这个模块可以在Gist上找到:https://gist.github.com/MattSurabian/7868115
使用以上模块并利用Promise解决方案返回google.maps:
define([ 'app/lib/google-maps-loader' ], function(GoogleMapsLoader){
GoogleMapsLoader.done(function(GoogleMaps){
// your google maps code here!
var geocoder = new GoogleMaps.Geocoder();
}).fail(function(){
console.error("ERROR: Google maps library failed to load");
});
});
或者,只需正常引用google.maps
对象即可。
define([ 'app/lib/google-maps-loader' ], function(GoogleMapsLoader){
GoogleMapsLoader.done(function(){
// your google maps code here!
var geocoder = new google.maps.Geocoder();
}).fail(function(){
console.error("ERROR: Google maps library failed to load");
});
});
我在这里写了一篇关于这种方法的简短博客文章,可能会对您有所帮助:RequireJS项目和异步加载Google Maps API
require.config({
googlemaps: {
params: {
key: 'abcd1234', // sets api key
libraries: 'geometry' // set google libraries
}
}
});
require(['googlemaps!'], function(gmaps) {
// google.maps available as gmaps
var map = new gmaps.Map('map-canvas');
});
gmaps
?清除监听器怎么样? - Muhaimin
http://maps.google.com/maps/api/js?key=<MY_KEY>&sensor=false
- maxwell2022