Skip to content

Instantly share code, notes, and snippets.

@pstadler
Last active March 14, 2016 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pstadler/28a79354d6a37d735b82 to your computer and use it in GitHub Desktop.
Save pstadler/28a79354d6a37d735b82 to your computer and use it in GitHub Desktop.
Simple on-demand lazy loader for the Google Maps Geocoding service
/**
* Geocoder is a simple on-demand lazy loader for the Google Maps Geocoding service
*
* Usage: `Geocoder.call(function (geocoder) {});`
*/
var Geocoder = (function (self) {
var _geocoder = null;
self.call = function (cb) {
// available
if (_geocoder) {
cb(_geocoder);
return;
}
// maps api available
if (window.google && window.google.maps) {
_geocoder = new google.maps.Geocoder;
cb(_geocoder);
return;
}
// maps api unavailable -- load it
var callbackId = 'geocoder_' + Math.random().toString(36).slice(2);
window[callbackId] = function () {
_geocoder = new google.maps.Geocoder;
cb(_geocoder);
};
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//maps.google.ch/maps/api/js?v=3.9&sensor=false&callback=' + callbackId;
document.body.appendChild(script);
};
return self;
})(Geocoder || {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment