2013-08-20 77 views
0

我试图实现一个谷歌地图V3异步映射到我的网站,并把它几乎等同于如何。虽然没有地图加载在页面上!有没有人在这里看到任何错误?异步映射不加载?

<script type="text/javascript"> 

google.maps.visualRefresh = true; 

function initialize() { 
    var mapOptions = { 
    zoom: 18, 
    center: new google.maps.LatLng(42.7870,-86.1023), 
    mapTypeId: google.maps.MapTypeId.SATELLITE 
    }; 

    var map = new google.maps.Map(document.getElementById('map-canvas'), 
     mapOptions); 

} 

function loadScript() { 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = 'https://maps.googleapis.com/maps/api/js?sensor=false' + 
     'callback=initialize'; 
    document.body.appendChild(script); 
} 

window.onload = loadScript; 

</script> 

<div id="map-canvas"></div> 

该页面的CSS是非常简单的:

html, body, #map-canvas { 
    margin: 0; 
    padding: 0; 
    height: 100%; 
} 

有什么想法?

+0

看看你的javascript错误'错误:谷歌没有定义'。解决这个问题:'Google Maps API服务器拒绝了您的请求。请求中指定的“传感器”参数必须设置为“true”或“false”。“修复该问题并显示地图。 – geocodezip

回答

1

有2个问题。

  1. 移动此行

    google.maps.visualRefresh = true;

    到开始的initialize。当你异步加载API时,google在执行该行时仍然未定义(你的调试器应该告诉你这个),这个错误将阻止所有后续指令的执行。

  2. script.src = 'https://maps.googleapis.com/maps/api/js?sensor=false' + 'callback=initialize';

    添加一个符号后false

+0

这是非常丰富和有益的。非常感谢!我希望我能够让你高兴,但我需要更多的信誉。再次感谢! – xd1936

0

Sometines比较好直接去源,而不是使用谷歌:)

呦可以看看源代码,他们正在使用和学习。之后,你可以谷歌。

https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

在这个例子中,他们使用syncronous负载为谷歌地图库。

你可以喜欢加载asyncronous然后用这样的方式:

·第一添加div和你的初始化函数:

<div id="map" style="width: 100%; height: 480px;"></div> 
<script type="text/javascript"> 
    function initialize() { 
     var mapOptions = { 
      zoom: 18, 
      center: new google.maps.LatLng(42.7870,-86.1023), 
      mapTypeId: google.maps.MapTypeId.SATELLITE 
     }; 

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
} 

注意:您不需要使用谷歌.maps.visualRefresh = true;谷歌在这里说: https://developers.google.com/maps/documentation/javascript/basics

·第二个地方的脚本异步加载和头或最后一行之前的标记的en。这会使页面的快速加载速度加快。

<script type="text/javascript"> 
    (function() { 
     var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; 
     po.src = 'https://maps.googleapis.com/maps/api/js?v=3&sensor=false&callback=initialize'; 
     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); 
    })(); 
</script>