I am building an iPhone app relying on the ionic-framework. The app uses Google maps and Google places. I have written the following angular service that loads the relevant scripts from Google asynchronously. I want to make sure that the app does not break when it starts up and there is no internet connection. I use the method
isLoadedGoogleMaps()
before I invoke any Google maps/places methods.
Could you please suggest any improvements? For instance, it seems that
( navigator.connection.type === Connection.NONE )
evaluates to false even though there is no internet connection in certain situations. Is there a better way of checking if the app is online?
.factory( 'GoogleMaps', [ '$ionicPlatform', '$window', function ( $ionicPlatform, $window ) {
var
// private methods
loadGoogleMaps,
initGoogleMaps,
// public method
isLoadedGoogleMaps;
// without defining this callback, the script loaded from Google would use the method document.write
// but an externally loaded script is not allowed to invoke document.write (observed when testing in browser)
window.globalGoogleMapsCallback = function () {
console.log( 'loaded GoogleMaps asynchronuously' );
alert( 'loaded GoogleMaps asynchronuously' );
};
// Begin private method /loadGoogleMaps/
loadGoogleMaps = function () {
var
script;
if ( ( typeof google === 'object' && typeof google.maps === 'object') // Google maps has already been loaded
|| // or
( navigator.connection.type === Connection.NONE ) // no internet connection
) {
alert( 'loadGoogleMaps exited because ' +
'Google Maps: ' + ( typeof google === 'object' && typeof google.maps === 'object') + ', ' +
'connection type none: ' + ( navigator.connection.type === Connection.NONE )
);
return;
}
alert( 'loadGoogleMaps is trying to download Google maps' );
// load script asyncronuously
script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' + 'libraries=places&' + 'callback=globalGoogleMapsCallback';
// append to body and not to head
document.body.appendChild( script );
};
// End private method /loadGoogleMaps/
// Begin private method /initGoogleMaps/
initGoogleMaps = function () {
$ionicPlatform.ready( function () {
// add online event
$ionicPlatform.on( 'online', function () {
loadGoogleMaps();
});
// load Google Maps at init because there is no initial online event
loadGoogleMaps();
});
};
// End private method /initGoogleMaps/
// Begin public method /getGoogleMaps/
isLoadedGoogleMaps = function () {
return (typeof google === 'object' && typeof google.maps === 'object');
};
// End public method /getGoogleMaps/
// init service
initGoogleMaps();
// expose public methods
return {
isLoadedGoogleMaps : isLoadedGoogleMaps
};
}])