检查谷歌地图是否可以访问Javascript

check if google maps can be reached Javascript

本文关键字:访问 Javascript 谷歌地图 是否 检查      更新时间:2023-09-26

我正在使用phonegap开发一个移动应用程序。我想开发它的线上和线下版本。在在线版本中,应用程序连接到谷歌地图API,在离线版本中,它应该跳过加载地图,继续加载页面元素的其余部分。我如何检查连接到谷歌地图API。

我有以下函数来加载地图:

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);

当我运行应用程序时,有互联网连接,它工作得很好,但当没有连接时,它给出错误"谷歌未定义",它也不加载页面。请告诉我如何检查连接。我试过用navigator。在线,但它是没有用的。谢谢!

#Option 1

既然你提到了PhoneGap,我建议你使用网络连接API,这是由PhoneGap提供的。

帮助您快速检查网络状态,以及蜂窝网络信息。

#选项2

你可以简单地把@DaveS在这个答案中提到的检查

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

你可以这样做:

<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
}