javascript - 如何确保我的应用程序可以在没有互联网连接的情况下与 Google map 等外部库配合使用?

标签 javascript android google-maps ionic-framework

我目前正在使用 Ionic 框架版本 1 开发移动应用程序。在此应用程序中,我使用 Google map 来显示 map 。该 map 正在使用脚本标签加载,并且在设备连接到互联网时运行良好。但是,如果应用程序在没有互联网连接的情况下启动,则应用程序甚至无法打开。我该如何解决这个问题?

最佳答案

我不确定为什么当无法加载库时 Ionic 应用程序根本拒绝打开,但幸运的是这个问题可以解决。

TL;DR:您必须异步加载 Google map ,因此请检查是否有网络连接以及是否加载库,否则会显示错误。

<小时/>

有很多关于如何异步加载 Google map 库的示例,例如 this post from Google ,或this question which contains an answer to your questionthis question in which the differences between loading using the script tag and loading asynchronously are explained 。还有this question in which it is shown using plain JavaScript .

当然,有很多文字需要阅读,所以这里是摘要。而不是在index.html中添加脚本标签,您必须仅在有互联网连接时加载 Google map 库,并使用 JavaScript 加载该库。为了检查 Activity 的互联网连接,您将需要 cordova-plugin-network-information ,您可以找到 here 。您还可以使用ngCordova为了更方便地使用这个插件,你可以找到文档here .

在您的 Controller 中,您可以执行以下操作:

.controller('MapCtrl', function($state, $scope, $window, $ionicPlatform) {

  // This view event is fired only when the view is loaded for the first time.
  $scope.$on("$ionicView.loaded", function(scopes, states) {
    var isMapLoaded = false;
    var networkState = navigator.connection.type;
    var isOnline = (networkState !== Connection.UNKNOWN && networkState !== Connection.NONE);

    if(isOnline) {
      // If there is a network connection, we load the map.
      var mapsURL = 'https://maps.googleapis.com/maps/api/js?key=[INSERT API KEY HERE]&callback=';

      $window.mapLoaded = function() {
        isMapLoaded = true;
        console.log("The map has been loaded.");
      }

      function loadMapsLibrary(url, callbackFunctionString) {
        var script = document.createElement('script');

        script.type = 'text/javascript';
        script.src = url + callbackFunctionString;

        document.body.appendChild(script);
      }

      $scope.isMapLoaded = isMapLoaded;

      loadMapsLibrary(mapsURL, "mapLoaded");
    } else {
      // It's up to you what you do here, you can show an error for example.
    }

在您看来,您可能必须使用 ng-if指令和 isMapLoaded重新加载值<div>包含 map 以确保其加载。这应该能让您大致了解需要做什么才能让您的应用再次运行。

关于javascript - 如何确保我的应用程序可以在没有互联网连接的情况下与 Google map 等外部库配合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40989967/

相关文章:

javascript - 无需加载页面即可交换内部图库和 HTML

javascript - Jquery 控制菜单在所有菜单上显示箭头,即使是没有子菜单的菜单

android - NestedScroll 内的可点击 CardView 不会触发滚动

c# - 如何在 xamarin.forms pcl 项目中配置 map ?

ios - 使用 url 方案将标记添加到 ios 中的谷歌地图

javascript - 仅在 Google map 嵌入的 map 上收听点击

javascript - 在 Yii 中使用 JavaScript(XWF/SWF 图表)

javascript - 如何按属性值聚合/分组对象数组?

android - 如何在 fragment 中绑定(bind)动态 View ?

android - 应用 LayoutParams 隐藏 View