javascript 首次未加载 Google 地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15872705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:24:09  来源:igfitidea点击:

Google Map is not loading for the first time

javascriptjquerygoogle-mapsjquery-mobilegoogle-maps-api-3

提问by Chrishan

I am using Google Maps JavaScript API to load map inside my mobile website. When I navigate from the previous page map won't load but if I refresh the page map load as expected. If I use the JavaScript inside the body even the page is not loading. I can't figure out the problem. Is it something with the previous page code ?

我正在使用 Google Maps JavaScript API 在我的移动网站中加载地图。当我从上一页导航时不会加载,但如果我按预期刷新页面地图加载。如果我在正文中使用 JavaScript,即使页面没有加载。我无法弄清楚问题所在。是否与前一页代码有关?

Here is my code in Head tag.

这是我在 Head 标签中的代码。

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" type="text/css" href="css/jquery.mobile-1.1.0.min.css" />  
<link href="css/site.css" rel="stylesheet" type="text/css" />
<script src="./js/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" 
src="http://maps.googleapis.com/maps/api/js?key=xxxxxxxx&sensor=false">
</script>
        <script type="text/javascript">
            function initialize() {
                var myLatlng = new google.maps.LatLng(<?php echo $longtitude ?>, <?php echo $latitude ?>);

                var mapOptions = {
                  zoom: 10,
                  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: 'Location'
                });
            }
             google.maps.event.addDomListener(window, 'load', initialize);

             $(document).delegate('#content', 'pageinit', function () {
               navigator.geolocation.getCurrentPosition(initialize);
                });
        </script>
</head> 

Here is my Body Tag

这是我的身体标签

<body >
    <div id="wrapper">
        <div class="header">
            <a href="index.html"><img src="images/logo-small.png" alt="logo"/></a>
        </div>
        <div class="back">
        <a data-rel="back"><img src="images/back.png"/></a>
    </div> 
        <div id="content">
            <div class="list">
                <div class="list-items" id="info">
                    <?php echo "<h3>$sa1<span>$postcode<span>$sa2</span></span></h3><h2>$price</h2>";?>
                <br class="clear" />
                <br class="clear" />
                </div>
            </div>
            <br class="clear" />
        <div id="map-canvas">
        </div>
    </div>
    </div>
</body>

I refer question Thisand Thisbut it's not working with my code.

我参考了这个这个问题,但它不适用于我的代码。

回答by Gajotres

Problems

问题

First of all, why are you using jQuery Mobile? I don't see the point in your current example.

首先,你为什么使用jQuery Mobile?我在您当前的示例中没有看到重点。

In this case jQuery Mobile is the main problem. Because jQuery Mobile is used everything will be loaded into the DOM. When you "navigate from the previous page" page is not refreshed and this line:

在这种情况下,jQuery Mobile 是主要问题。因为使用了 jQuery Mobile,所以所有东西都将被加载到 DOM 中。当您“从上一页导航”页面未刷新且此行时:

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

can't trigger. It will trigger only if you manually refresh the page.

不能触发。仅当您手动刷新页面时才会触发。

Second thing, you cant use jQuery Mobile page events without having any page what so ever. In your code you have this part:

第二件事,你不能在没有任何页面的情况下使用 jQuery Mobile 页面事件。在您的代码中,您有这一部分:

$(document).delegate('#content', 'pageinit', function () {
    navigator.geolocation.getCurrentPosition(initialize);
});

For it to initialize successfully div with an id content MUST have another attribute called data-role="page", like this:

为了它成功初始化带有 id 内容的 div 必须有另一个名为 data-role="page" 的属性,如下所示:

<div id="content" data-role="page">

</div>

Third thing. Lets assume everything else is ok. Pageinit will not trigger from the HEAD. When jQuery Mobile loads pages it loads them into the DOM and only BODY part will be loaded. So for your map to work you need to move our javascript to the BODY (including a css). In you first example it didnt worked because you were triggering page even on a non-page div container.

第三件事。让我们假设其他一切正常。Pageinit 不会从 HEAD 触发。当 jQuery Mobile 加载页面时,它会将它们加载到 DOM 中,并且只会加载 BODY 部分。因此,为了让您的地图工作,您需要将我们的 javascript 移动到 BODY(包括一个 css)。在您的第一个示例中,它不起作用,因为您甚至在非页面 div 容器上也触发了页面。

And last thing, if you want to use jQuery Mobile properly you will need to take care correct version of jQuery is used with a correct version of jQuery Mobile. If you want to be safe use jQ 1.8.3 with jQM 1.2

最后一件事,如果您想正确使用 jQuery Mobile,您需要注意正确版本的 jQuery 与正确版本的 jQuery Mobile 一起使用。如果你想安全使用 jQ 1.8.3 和 jQM 1.2

Solution

解决方案

Here's a working solution:

这是一个有效的解决方案:

<!DOCTYPE html>
<html>
    <head>
        <title>jQM Complex Demo</title>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>          
        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>                  
    </head>
    <body>
        <style>
            #map-canvas {
                width: 300px;
                height: 300px;
            }
        </style>            
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>       
        <script type="text/javascript">
            function initialize() {     
                var myLatlng = new google.maps.LatLng(33.89342, -84.30715);

                var mapOptions = {
                  zoom: 10,
                  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: 'Location'
                });
            }

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

            $(document).on('pageshow', '#wrapper', function(e, data){       
                initialize();
            });             
        </script>   
        <div id="wrapper" data-role="page">
            <div class="header">
                <h3>Test</h3>
                <a href="index.html"><img src="images/logo-small.png" alt="logo"/></a>
            </div>
            <div id="content">
                <div id="map-canvas"></div>
            </div>
        </div>  
    </body>
</html>   

Working examples and much more information regarding this topic can be found in this ARTICLE.

在这篇文章中可以找到关于这个主题的工作示例和更多信息。

回答by Amir Shirazi

just add: data-ajax="false"to the link tag which redirects to the page that contains your map. for example, if map.aspx contains your map, you can link to it like this:

只需添加:data-ajax="false"到重定向到包含您的地图的页面的链接标签。例如,如果 map.aspx 包含您的地图,您可以像这样链接到它:

<a href="map.aspx" data-ajax="false">

回答by Bhojendra Rauniyar

I was having same problem but I have no any jquery-mobile libraray or any other which would conflict the map. Struggling a hard time, I found a solution for my project:

我遇到了同样的问题,但我没有任何 jquery-mobile 库或任何其他会与地图冲突的库。苦苦挣扎,我为我的项目找到了解决方案:

Doesn't work:

不起作用:

<script src="http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" async defer>
</script>

Works (Removing async and defer attributes):

有效(删除 async 和 defer 属性):

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

Hope! This helps someone if the other solutions doesn't work. Try this only if none of other solution work because it is not good suggestion as we know google page speed guide or google map api guide says to use it.

希望!如果其他解决方案不起作用,这会对某人有所帮助。仅当其他解决方案均无效时才尝试此操作,因为这不是好的建议,因为我们知道 google 页面速度指南或 google map api 指南说要使用它。

回答by Jignesh Darji

I have also same problem with google.maps.event.addDomListener(window, 'load', initialize);where initialize is my method . I just add few line of code before google.maps.event.addDomListener(window, 'load', initialize);

我也有同样的问题, google.maps.event.addDomListener(window, 'load', initialize);其中 initialize 是我的方法。我之前只加了几行代码google.maps.event.addDomListener(window, 'load', initialize);

Code is

代码是

 $(document).ready( function () {
        initialize();
    });

and this code is working for me

这段代码对我有用

回答by jakobhans

You should use the pageloadevent to load everything. This way everything is loaded once jquery Mobile has done all the DOM changes it needs. I've had this same problem and that's what helped.

您应该使用该pageload事件来加载所有内容。这样,一旦 jquery Mobile 完成了它需要的所有 DOM 更改,所有内容都会加载。我遇到了同样的问题,这就是帮助。

$(document).on('pageload', function() {
  initialize();
});

It's in the docs: http://api.jquerymobile.com/pageload/

它在文档中:http: //api.jquerymobile.com/pageload/

EDIT: Sometimes it also helps to load the markers in a separate function than the one loading the map.

编辑:有时它也有助于在一个单独的函数中加载标记而不是加载地图。