我目前正在使用 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 question或this 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/