谷歌地图无法在科尔多瓦加载

2024-03-16

目前我正在尝试构建一个应该使用谷歌地图的 Cordova 应用程序,以便我可以显示路线和内容。出于测试原因,我还在服务器上放置了代码,一切都运行良好,地图可能正在加载。但是当我将项目转换为 Cordova 应用程序时,谷歌地图无法加载,我不知道为什么。

这就是我在index.html 中的JS 代码的样子:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta charset="utf-8">
    <title>-----</title>
    </head>

    <!-- jQuery Version 1.11.0 -->
    <script type="application/javascript" src="./js/jquery-1.11.0.js"></script>

    <!-- Google Maps API -->
      <script type="text/javascript"
      src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCr0wsx4a5_o03hPTpC_CtRARjzCnOEGX4&sensor=false&libraries=places">
    </script>

    <!-- Style CSS -->
    <link href="./css/style.css" rel="stylesheet">

    <script>


var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

if(isMobile.any()) {

   (function (global) {
    "use strict";

    function onDeviceReady () {
        document.addEventListener("online", onOnline, false);
        document.addEventListener("resume", onResume, false);
        loadMapsApi();
    }

    function onOnline () {
        loadMapsApi();
    }

    function onResume () {
        loadMapsApi();
    }

    function loadMapsApi () {
        if(navigator.connection.type === Connection.NONE || google.maps) {
            return;
        }
        $.getScript('http://maps.googleapis.com/maps/api/js?key=AIzaSyCr0wsx4a5_o03hPTpC_CtRARjzCnOEGX4&sensor=false&libraries=places');
    }

    global.onMapsApiLoaded = function () {
        // Maps API loaded and ready to be used.
        var map = new google.maps.Map(document.getElementById("map"), {});
    };

    document.addEventListener("deviceready", onDeviceReady, initialize);
})(window);
alert("");
}


function initialize() {
 var styles = [{"featureType":"water","elementType":"all","stylers":[{"hue":"#76aee3"},{"saturation":38},{"lightness":-11},{"visibility":"on"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"hue":"#8dc749"},{"saturation":-47},{"lightness":-17},{"visibility":"on"}]},{"featureType":"poi.park","elementType":"all","stylers":[{"hue":"#c6e3a4"},{"saturation":17},{"lightness":-2},{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"all","stylers":[{"hue":"#cccccc"},{"saturation":-100},{"lightness":13},{"visibility":"on"}]},{"featureType":"administrative.land_parcel","elementType":"all","stylers":[{"hue":"#5f5855"},{"saturation":6},{"lightness":-31},{"visibility":"on"}]},{"featureType":"road.local","elementType":"all","stylers":[{"hue":"#ffffff"},{"saturation":-100},{"lightness":100},{"visibility":"simplified"}]},{"featureType":"water","elementType":"all","stylers":[]}];
 var styledMap = new google.maps.StyledMapType(styles, {name: ""});

  directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: {
      strokeColor: "red"
    }});
  var mapOptions = {
          center: new google.maps.LatLng(47.6826215,13.0984208,17),
          zoom: 15,
          disableDefaultUI: true,
          mapTypeControlOptions: {
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
            }
        };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        map.mapTypes.set('map_style', styledMap);
        map.setMapTypeId('map_style');
        map.setOptions({styles: styles});

    var defaultBounds = new google.maps.LatLngBounds(
          new google.maps.LatLng(47.67052,13.114028),
          new google.maps.LatLng(47.6910273,13.1153865));

        var options = {
          bounds: defaultBounds,
        };

        var start_input = document.getElementById('start');
        start_autocomplete = new google.maps.places.Autocomplete(start_input, options);
    var end_input = document.getElementById('end');
        end_autocomplete = new google.maps.places.Autocomplete(end_input, options);

  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

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

    </script>

您发布的示例不起作用可能有多种原因:

  • 谷歌地图加载事件:

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

    在网络应用程序中立即似乎是个好主意,但即使我在其中使用了 domlistener设备就绪它不起作用。但这可能是 cordova-apps 异步加载 google-library 的更好解决方案:

    function loadAsynchronousScript() {
       var script = document.createElement('script');
       script.type = 'text/javascript';
       script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +'&signed_in=true&callback=initialize';
       document.body.appendChild(script);
    }
    

    我测试过你甚至可以打电话初始化独自在里面设备就绪但使用起来要好很多加载异步脚本因为它为您完成 domlistener 的工作,因此它知道库何时准备就绪(参数:&回调=)。在上面的例子中加载异步脚本加载标准库,但您也可以将其替换为具体的键控库。

    参考:https://developers.google.com/maps/documentation/javascript/examples/map-simple-async https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

  • 插入谷歌地图多次错误:

    在您的示例中,您检查该库是否存在,但我什至遇到了问题,因此在我的示例中,我省略了index.html中的脚本标签:

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=...."></script>
    

    但在我的示例中,无论如何都不需要这个标签。

  • 我没有看到您在其上调用地图的 div-tag(id: 'map-canvas') 。但可能是我忽略了它。我还省略了 calcRoute-function ,因为您没有在任何地方调用它,并且它不是原始问题的一部分。

不幸的是我改变了你的一些代码片段,它在我的android-emulator 但我无法在 IOS 设备上测试它:

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        document.addEventListener("online", onOnline, false);
        document.addEventListener("resume", onResume, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        
        console.log('Received Event: ' + id);
        
        if(isMobile.any()) {
        	
	        if(googleLibExists()){
	        	initialize();
	        }
	        else{
	        	loadMapsApi();
	        }
	        
        }
        
    }
};

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows();
    }
};

function googleLibExists(){
	return typeof(google) != "undefined" && google.maps;
}

function loadAsynchronousScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'http://maps.googleapis.com/maps/api/js?key=AIzaSyCr0wsx4a5_o03hPTpC_CtRARjzCnOEGX4&sensor=false&libraries=places&callback=initialize';
  document.body.appendChild(script);
}


function loadMapsApi () {
    if(navigator.connection.type === Connection.NONE) {
		  alert('google maps library not loaded');
        return;
    }
    if(!googleLibExists()){
	    loadAsynchronousScript();
    }
}

function onOnline () {
    loadMapsApi();
}

function onResume () {
    loadMapsApi();
}

var directionsDisplay;
var map;

function initialize() {
	
	console.log('map init');
	
	 var styles = [{"featureType":"water","elementType":"all","stylers":[{"hue":"#76aee3"},{"saturation":38},{"lightness":-11},{"visibility":"on"}]},{"featureType":"road.highway","elementType":"all","stylers":[{"hue":"#8dc749"},{"saturation":-47},{"lightness":-17},{"visibility":"on"}]},{"featureType":"poi.park","elementType":"all","stylers":[{"hue":"#c6e3a4"},{"saturation":17},{"lightness":-2},{"visibility":"on"}]},{"featureType":"road.arterial","elementType":"all","stylers":[{"hue":"#cccccc"},{"saturation":-100},{"lightness":13},{"visibility":"on"}]},{"featureType":"administrative.land_parcel","elementType":"all","stylers":[{"hue":"#5f5855"},{"saturation":6},{"lightness":-31},{"visibility":"on"}]},{"featureType":"road.local","elementType":"all","stylers":[{"hue":"#ffffff"},{"saturation":-100},{"lightness":100},{"visibility":"simplified"}]},{"featureType":"water","elementType":"all","stylers":[]}];
	 var styledMap = new google.maps.StyledMapType(styles, {name: ""});
	
	  directionsDisplay = new google.maps.DirectionsRenderer({polylineOptions: {
	      strokeColor: "red"
	    }});
	  var mapOptions = {
	          center: new google.maps.LatLng(47.6826215,13.0984208,17),
	          zoom: 15,
	          disableDefaultUI: true,
	          mapTypeControlOptions: {
	            mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
	            }
	        };
	  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	        map.mapTypes.set('map_style', styledMap);
	        map.setMapTypeId('map_style');
	        map.setOptions({styles: styles});
	
	    var defaultBounds = new google.maps.LatLngBounds(
	          new google.maps.LatLng(47.67052,13.114028),
	          new google.maps.LatLng(47.6910273,13.1153865));
	
	        var options = {
	          bounds: defaultBounds,
	        };
	
	        var start_input = document.getElementById('start');
	        start_autocomplete = new google.maps.places.Autocomplete(start_input, options);
	    var end_input = document.getElementById('end');
	        end_autocomplete = new google.maps.places.Autocomplete(end_input, options);
	
	  directionsDisplay.setMap(map);
}
<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <title>Hello World</title>
    </head>
    <body>
        
        <h1>Map:</h1>
        <div id="map-canvas" style="width:200px; height:200px"></div>
        
        <script type="application/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>

	    
	<script type="text/javascript" src="cordova.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
        <script type="text/javascript">
            app.initialize();
        </script>
    </body>
</html>

证据图片:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

谷歌地图无法在科尔多瓦加载 的相关文章

随机推荐

  • 如何获取Scala函数的参数/返回类型?

    我有一个函数 想要获取它的参数类型和返回类型以在 Scala 宏中使用 scala gt val fn a String b Double gt 123 fn String Double gt Int
  • 尝试远程连接到 websphere 上的 JMS 队列时出现 sun/io/MalformedInputException

    我知道 非常 类似的问题 https stackoverflow com questions 27272877 how to solve sun io malformedinputexception during jndi lookup o
  • 找不到模块“反应”

    我正在尝试将 React 集成到现有的网页中 目前 我无法加载我的 React 应用程序 我的 React 应用程序有两个文件 这时 他们的样子是这样的 myApp js import React from react import Rea
  • 使用 python 2.5 安装 django,而不是使用默认版本的 python

    我必须在我的 Linux 服务器上安装 Django 其中 python 2 4 可作为默认安装 我已经安装了 python 2 5 作为单独的版本 现在我必须安装 Django 我必须将其与 python 2 5 一起使用 是否有任何特定
  • 将数据类型 varchar 转换为数字动态数据透视表时出错

    我收到标题中描述的错误 其中我的代码如下所示 declare cols numeric 10 0 sql numeric 10 0 select cols isnull cols T AmountPayd from select disti
  • 将 AST 节点转换为 python 代码

    假设我有以下字符串 code if 1 1 and 2 2 and 3 3 test 1 以下代码将该字符串转换为 AST ast parse code 然后我有一棵树 Module body lt ast If object at 0x1
  • 如何使用 Firebase 刷新令牌来持久进行身份验证?

    我几周来一直试图解决这个问题 但似乎无法理解文档或其他东西 我很感激你能提供的任何帮助 我正在使用 Firebase SDK 我有我的服务器端路由 我可以在其中访问令牌并将其发送到前端 const admin require firebas
  • 如何正确获取在 AppEngine 上运行的 NodeJS 中的云功能的令牌?

    我在获取正确的令牌来触发我的云功能时遇到问题 通过 POSTMAN 测试时 我通过运行以下命令获取令牌 gcloud auth print identity token 我的功能工作正常 但在我的服务器上我使用以下代码 我也确实看到了该令牌
  • 2 个相互关联的案例陈述

    我对 SQL 编码比较陌生 并且有一个关于 case 语句的问题 我想要实现的目标 我想创建一个用于计算正确的过时规定的查询 为此 我需要创建一个名为的列Inventory Reach和一个叫Devaluation Class 这两个字段都
  • 如何导入和导出 JBPM 6.5 存储库

    我想问您是否知道如何在不同的 Kie Workbench 之间导出和导入 JBPM 项目 我正在使用 JBPM 6 5 谢谢 使用 Git 可能是唯一合理的方法 按照此顺序 可以将项目放入 git 存储库 然后将其导入到其他实例 在装有 j
  • 抛出检查异常

    我在Java中的一些方法会抛出异常 例如NoSuchElementException IllegalArgumentException等 但是当使用这些方法时 这些异常似乎是未经检查的 换句话说 我的方法的调用者不需要对抛出这些异常的方法执
  • 在 Ruby on Rails 5 中禁用 ActiveRecord

    我是 Rails 的新手 我想在 Rails 5 中禁用 ActiveRecord 我已经找到了几个答案Here https stackoverflow com questions 28319002 how do i remove acti
  • 将整数列表传递给 GET REST API

    我想从前端的数据库中获取实体列表 所以我在 Spring MVC 中编写了 POST REST HTTP 调用 但我读过 HTTP 文档 其中说每当您必须从数据库检索数据时 更喜欢 GET 调用 那么 是否有任何我可以将 Angular J
  • 如何在android中加载低质量然后高质量的图像(就像WhatsApp个人资料图像)

    我正在寻找一种可以使用的设计模式 以便在 android recyclerView 中我可以以低质量快速加载图像 然后还可以调用高质量图像将 之后重写低质量图像 我经常看到先加载低质量图像 然后再加载高质量图像 但是 这是如何在回收器视图的
  • Javascript 在日期对象本身中设置时区,如 setTimeOffset() [重复]

    这个问题在这里已经有答案了 我想更改 Date 对象本身的时区 因为设备 网络浏览器 本身不支持时区 我怎么改变它 例如 var date new Date Value is Mon Jun 19 2017 10 00 08 GMT 000
  • Android 显式 Intent 抛出 NoClassDefFounderror

    我正在尝试使用明确的意图在我的 Android 应用程序中显示 MapView 尽管我没有发现我的代码有任何问题 但当我尝试启动我的活动时 我不断收到 NoClassDefFoundError 基本上 从我的主要活动 SetCriteria
  • 多线程Python网络爬虫卡住了

    我正在编写一个Python网络爬虫 我想让它成为多线程的 现在我已经完成了基本部分 以下是它的作用 一个线程从队列中获取一个url 线程从页面中提取链接 检查链接是否存在于池 集合 中 并将新链接放入队列和池中 该线程将 url 和 htt
  • 在 angularjs 中提交时显示验证错误消息

    我有一个表单 如果单击 提交 则需要显示验证错误消息 这是一个工作plunker http plnkr co edit nYPzEO8d3SKuFk4KBn1o p preview
  • 在没有 numpy polyfit 的情况下在 python 中拟合二次函数

    我正在尝试将二次函数拟合到某些数据 并且我尝试在不使用 numpy 的 polyfit 函数的情况下执行此操作 从数学上讲我试图关注这个网站https neutrium net mathematics least squares fitti
  • 谷歌地图无法在科尔多瓦加载

    目前我正在尝试构建一个应该使用谷歌地图的 Cordova 应用程序 以便我可以显示路线和内容 出于测试原因 我还在服务器上放置了代码 一切都运行良好 地图可能正在加载 但是当我将项目转换为 Cordova 应用程序时 谷歌地图无法加载 我不