devop
devop

Reputation: 49

check if google maps can be reached Javascript

I am developing a mobile app using phonegap. I want to develop online as well as offline version of it. In online version, the App connects to google maps API and in offline version, it should skip loading the Maps and continue loading rest of the page elements. How can I check the connectivity to google maps API.

I have following function to load the Maps:

function initialize() {
    var myLatlng = new google.maps.LatLng(98,-33);
    var mapOptions = {
        zoom: 11,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

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

    var infowindow = new google.maps.InfoWindow({

      content: "<div style='width:80px;'>Your Location</div>",
      minWidth: 500 
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.open(map,marker);
  });    

}

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

When I run the App when there is internet connection, it works fine, but when there is no connection, it gives error 'Google is not defined' and it doesn't load the page as well. Please tell how to check the connection. I tried using navigator.onLine, but it isn't useful. Thanks!

Upvotes: 1

Views: 1998

Answers (2)

Praveen
Praveen

Reputation: 56509

#Option 1

Since you mentioned PhoneGap I would suggest you to go with Network Connection API that is being provided by PhoneGap.

Which help you to quickly check the network state, and cellular network information.

#Option 2

You can simple put a check as mentioned by @DaveS in this answer

if (typeof google === 'object' && typeof google.maps === 'object') {
    // Google maps loaded
    initialize();
} else {
    // Failed to load the Google Maps
}

Upvotes: 1

SivaDotRender
SivaDotRender

Reputation: 1651

You could do something like this:

<script type="text/javascript" onload="loaded()" src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

function loaded(){

    //this will only execute if the page loads

}

Upvotes: 0

Related Questions