Last active
July 21, 2017 17:54
-
-
Save rutger1140/9831313 to your computer and use it in GitHub Desktop.
Javascript module pattern to 'lazy load' Google Maps asynchronous, with jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// global.js | |
// Global debug logger | |
var debug = true, | |
log = function(s){ | |
if(debug) { | |
console.log(s); | |
} | |
}; | |
// map.js | |
var map, | |
gmap = (function($){ | |
var s = { | |
mapDefaults: { | |
panControl: false, | |
zoomControl: true, | |
zoomControlOptions: true, | |
scaleControl: false, | |
mapTypeControl: false, | |
streetViewControl: false, | |
scrollwheel: false, | |
zoom: 12, | |
maxZoom: 16, | |
minZoom: 12 | |
}, | |
mapcanvas: 0, | |
// Coordinates for center of NL | |
latCenter : 51.810688, | |
lonCenter : 5.251171 | |
}; | |
function init(){ | |
log("gmap.init()"); | |
s.mapcanvas = $(".gmap"); | |
// Load Google Maps API async | |
if(s.mapcanvas.length) { | |
load(); | |
} else { | |
log("gmap.init(): no mapcanvas found"); | |
} | |
} | |
function load(){ | |
log("gmap.load()"); | |
var script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' + | |
'callback=gmap.build'; | |
document.body.appendChild(script); | |
} | |
function build(){ | |
log("gmap.build()"); | |
var mapOptions = $.extend({}, s.mapDefaults, { | |
zoom: s.zoom, | |
center: new google.maps.LatLng(s.latCenter,s.lonCenter), | |
maxZoom: s.maxZoom, | |
minZoom: s.minZoom, | |
styles: [] | |
}); | |
map = new google.maps.Map(s.mapcanvas[0], mapOptions); | |
} | |
return { | |
init: init, | |
build: build | |
} | |
})(jQuery); | |
// run gmap.init() onload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment