Sander Schaeffer
Sander Schaeffer

Reputation: 2827

Image fallback when there is no internet connection to load Google Map Canvas

I've got an application (WebApp) that is running local (of course). However, I can suggest users might have the app downloaded, but not always have 3G/WiFi when running the app. Therefor, the Google Map would not load when a user doesn't has an internet connection, since it needs the web API.

As a fallback, I would like to show an image ('screenshot') when the map could not be loaded.

What would be the most appropriate solution? Thanks!


The whole map canvas works with help of these code pieces

HTML

<div id="map-canvas"></div>

CSS

#map-canvas { 
width:100%;
height:200px;
}

Javascript

    function initialize() {
  var myLatlng = new google.maps.LatLng(51.81199,4.66656);
  var mapOptions = {
    zoom: 9,
    center: myLatlng
  }
  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Hello World!'
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
// END OF GOOGLE MAPS //

External Google API script

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

Upvotes: 0

Views: 1278

Answers (1)

Andy
Andy

Reputation: 63524

You wouldn't use the following line:

google.maps.event.addDomListener(window, 'load', initialize);

On window.onload you would check to see if google.maps exists and then use an if/else statement to toggle between the conditions - initialize, or load the image in the map's place. Something like:

window.onload = function () {
  var foundGoogle, img;
  foundGoogle = typeof google === 'object' && typeof google.maps === 'object';
  if (foundGoogle) {
    initialize();
  } else {
    img = new Image();
    img.src = 'screenshot.png';
    document.getElementById('map-canvas').appendChild(img);
  }
}

Upvotes: 3

Related Questions