I want download java Script google map API V3 and load them in HTML file from local host instead use them from google API online link. Because when I'm load API from google server and my device is offline my app has error in use of google API method for render to project. and I'm online after run app but map doesn't work and doesn't load image map.
If you start your app when offline, script tags will throw a net::ERRxxx. You can see this on browser console.
Later, when you come back online, those scripts have failed loading and that is it.
I have tackle this using setTimeout and google maps callback parameter. Basically, I remove and reinject the script tag on page every 5 seconds and set google maps callback to stop the cycle and execute a user callback.
So, as you stated, when you are back online, your script will load and your google maps API will be available inside the callback.
Try this:
loadAPI( function(map) {
console.log('back to business!');
//...
}
code:
var loadAPITimer = null;
function loadAPI(callback) {
var googleMapsScriptId = 'googleMapsScript';
if ( (typeof(loadAPITimer))==="undefined") {
throw('global vars are not defined');
}
if (window.google && window.google.maps) { // API already loaded
window.googleMapsLoadCallback(callback);
return;
}
if (loadAPITimer !== null) { //already running
return;
}
//inject script every 5 seconds
loadAPITimer = setInterval(function() { injectScript(); },5000);
//---- LOCAL FUNCTIONS --------------------------------------------
//---- google maps callback
window.googleMapsLoadCallback = function(cback) {
console.log('done! Inside googleMapsLoadCallback');
if (loadAPITimer) { //still running, cleanUp
clearInterval(loadAPITimer);
loadAPITimer = null;
} else {
console.log('google maps already loaded.');
}
cback && cback(window.google.maps);
}
//---- inject script tag for maps
function injectScript() {
if ( window.google && window.google.maps ) {
console.log('Google Maps Loaded!');
window.googleMapsLoadCallback(callback);
}
else if (window.google && window.google.load) {
console.log('google is defined: loading maps');
window.google.load('maps', version || 3, {'other_params': '&sensor=false' , 'callback' : 'googleMapsLoadCallback'});
}
else {
console.log('injecting Google Maps script');
var script = window.document.getElementById(googleMapsScriptId);
if (script) {
script.parentNode.removeChild(script);
}
window.setTimeout( function() {
script = window.document.createElement('script');
script.id = googleMapsScriptId;
script.type = 'text/javascript';
script.src = 'http://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=googleMapsLoadCallback';
window.document.body.appendChild(script);
}, 100 );
}
}
}