I'm using Gulp and Browserify to bundle my JavaScripts. I need to expose a callback function that should be executed after the Google Maps API loads.
How can this be done without using something like window.initMap? The problem with this is that I need to fire a large number of other methods inside initMap, so there has to be a better way of doing it besides using window.functionName and polluting the global namespace.
On the other hand, is it alright to just exclude the callback parameter and do something like this instead?
$.getScript('https://maps.googleapis.com/maps/api/js').done(function() {
initMap();
});
Any help would be greatly appreciated. I have spent more time that I would ever admit in getting this to work.
gulpfile.js:
gulp.task('browserify', ['eslint'], function() {
return browserify('/src/js/main.js')
.bundle()
.pipe(source('main.js'))
.pipe(buffer())
.pipe(gulp.dest('/dist/js'))
.pipe(reload({ stream: true }));
});
main.js:
require('jquery');
require('./map');
map.js:
var map = (function() {
'use strict';
var mapElement = $('#map');
function googleMapsAPI() {
$.getScript('https://maps.googleapis.com/maps/api/js?callback=initMap');
}
function initMap() {
var theMap = new google.maps.Map(mapElement);
// functions...
}
function init() {
googleMapsAPI();
}
});
map.init();