Reputation: 2218
I have an application in which deals with online/offline situations. Right now, I have some instances in which the application is first ran offline, and the api fails to load, which resulted in a blank map page.
The calling of the google map api would be something like this.
<script src="http://maps.google.com/maps/api/js?key=APIKEY"></script>
I have already added an event listener which deals with online/offline situations which is something like this
document.addEventListener("offline", function()
{
console.log("in offline event listener");
}, false);
document.addEventListener("online", function()
{
console.log("in online event listener");
}, false);
How do i check whether my google map api has been initialized and how do i reinitialize it?
Update 1: I'm able to insert script in runtime via,
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "http://maps.google.com/maps/api/js?key=APIKEY");
document.getElementsByTagName("body")[0].appendChild(script);
But this will cause multiple instances of google map api call in result in my other map plugins fail to work. Thus, I would still need to either destroy the failed map api call or check whether is the google map api is already successfully called and retrieved.
Upvotes: 2
Views: 4477
Reputation: 1396
Instead of restarting the script, you can try running it only when you have internet connection.
Remove the <script>...</script>
element from index.html
At your main page javascript:
key = "YOUR GOOGLE MAP API KEY"
GoogleMapInit(key);
function GoogleMapInit(key){
if (key != null){
apiKey = key;
}
loadGoogleMaps();
}
function loadGoogleMaps(){
window.mapInit = function(){
//Run any code that must be run after Google Map Api is done (E.g loading markers)
}
var script = document.createElement("script");
script.type = "text/javascript";
script.id = "googleMaps";
if (apiKey){
script.src = 'http://maps.google.com/maps/api/js?key=' + apiKey + '&callback=mapInit';
}
else{
script.src = 'http://maps.google.com/maps/api/js?callback=mapInit';
}
document.body.appendChild(script);
}
You can also refer to: https://www.joshmorony.com/part-3-advanced-google-maps-integration-with-ionic-and-remote-data/
Upvotes: 3