谷歌地图API显示空白地图

13

我相信这是一个基本问题,但我已经撞了太多次墙头,所以希望有人能同情我!

我有以下示例,但它只显示一个灰色的框,没有地图。有人能告诉我为什么吗?

我已经检查过我实际上是否返回了结果,而且似乎运行良好。

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

        <style>
            html, body, #map-canvas {margin: 0;padding: 0;height: 100%;}
        </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
      var geocoder;
      var map;

      function initialize() 
      {
        geocoder = new google.maps.Geocoder();        
        geocoder.geocode( { 'address': "England"}, function(results, status) 
        {
          if (status == google.maps.GeocoderStatus.OK) 
          {
            var mapOptions = {
              zoom: 8,
              center: new google.maps.LatLng(results[0].geometry.location),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            // Let's draw the map
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

          } 
          else 
          {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }

    initialize();
    </script>
  </head>

  <body onload="">
 <div id="map-canvas" style="width: 320px; height: 480px;"></div>
</body>
</html>    
7个回答

9
请尝试调整浏览器窗口大小,用鼠标在浏览器标签上晃动或拖动它,您会看到地图出现。

由于某种奇怪的原因,在MVC局部视图中,谷歌地图显示为空白,您的地图是正常工作的,只需要调整大小即可。

用鼠标在浏览器窗口中晃动听起来很有趣,但它确实有效,我不确定如何最好地描述它。

谢谢, Anurag

=======================================================================

我的最终可行代码如下:

`

<script type="text/javascript">

    $(document).ready(function () {
        (function () {
            var options = {
                zoom: 6,
                center: new google.maps.LatLng(-2.633333, 37.233334),
                mapTypeId: google.maps.MapTypeId.TERRAIN,
                mapTypeControl: false
            };

            // init map
            var map = new google.maps.Map(document.getElementById('map_canvas'), options);


            var arrLocation = [];
            $("#markerDiv").find("div").each(function () {
                var Lat = $(this).find("input[id='Latitude']").val();
                var Lon = $(this).find("input[id='Longitude']").val();
                var Id = $(this).find("input[id='Id']").val();
                var AssessmentDet = $(this).find("input[id='AssessmentDateTime']").val();
                var LocAcc = $(this).find("input[id='LocationAccuracy']").val();
                var assessorName = $(this).find("input[id='AssessorName']").val();
                var partnerName = $(this).find("input[id='PartnerName']").val();
                arrLocation.push({
                    Id: Id,
                    Latitude: Lat,
                    Longitude: Lon,
                    AssessmentDate: AssessmentDet,
                    LocationAccuracy: LocAcc,
                    AssessorDetail: assessorName,
                    PartnerName: partnerName
                    });
            });

            var allMarkers = [];

            for (var i = 0; i < arrLocation.length; i++) {

                //final position for marker, could be updated if another marker already exists in same position
                var latlng = new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude);
                var finalLatLng = latlng;
                var comparelatlng = "(" + arrLocation[i].Latitude + "," + arrLocation[i].Longitude + ")";
                var copyMarker = arrLocation[i];

                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude),
                    map: map,
                    title: 'Equine # ' + arrLocation[i].Id,
                    icon:"abc.png"
                });


                var markerInfo = "Reference # : <b>" + arrLocation[i].Id + "</b><br/>";
                markerInfo = markerInfo + "Assessor : <b>" + arrLocation[i].AssessorDetail + "</b><br/>";
                markerInfo = markerInfo + "Date :  <b>" + arrLocation[i].AssessmentDate + "</b><br/>";
                markerInfo = markerInfo + "Partner :  <b>" + arrLocation[i].PartnerName + "</b>";(function (marker, i) {

  bindInfoWindow(marker, map, new google.maps.InfoWindow(), markerInfo);
                })(marker, i);
            }
        })();
    });

    function bindInfoWindow(marker, map, infowindow, html) {
        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(html);
            infowindow.open(map, marker);
        });
    }


</script>

`


5
我也遇到了同样的问题,调整浏览器窗口大小可以使其完成加载。不知道为什么或该怎么解决。 - David K. Hess
1
哈哈,它能工作,但是背后的主要原因是什么呢,@Anurag? - Bibek Sharma
我目前正在与这种行为作斗争,并尝试了各种方法,如触发调整大小。我认为我的问题是由于在Angular UI路由器中DOM对象加载不正确引起的。 - user9903
我也遇到了同样的问题!有没有什么方法可以解决它? - Anand
@Anand,我通过创建一个 <DIV id="map"> 并通过 ajax 替换 div 内容为 _partial view 文本来使其工作,还要确保在您的 partial view 中指定了地图的中心点和缩放级别,如下所示,codevar options = { zoom: 6, center: new google.maps.LatLng(-2.633333, 37.233334), mapTypeId: google.maps.MapTypeId.TERRAIN, mapTypeControl: false }; // 初始化地图 var map = new google.maps.Map(document.getElementById('map_canvas'), options);code - Anurag
@Anurag,调整整个窗口的大小可以生效,但我看不出你的代码与调整大小有什么关系。对我来说,jQuery触发器没有用。这个起作用:window.dispatchEvent(new Event('resize'));。尽管最佳方法可能包括IE等的替代方案。 - Bob Stein

8

results[0].geometry.location 已经是一个 latLng 对象,因此您可以直接使用以下语句:

center: results[0].geometry.location

在这里找到可用的示例:http://jsfiddle.net/87z9K/

很好的发现,希望你不介意。我在你的答案中添加了一个fiddle以供OP验证。 - The Dark Knight
@putvande 那很好!只是为了我的参考,它在哪里创建latLng对象? - bencarter78

3
由于提供的“google.maps.LatLng”错误,导致出现问题。 提供测试坐标,它将正常工作。 替换该行。
center: new google.maps.LatLng(results[0].geometry.location),

使用

center: new google.maps.LatLng(-34.397, 150.644)

获得英格兰坐标。

1

虽然不是你的问题,但与之密切相关。

我发现必须使用一个有效的centre来设置地图选项,像这样:

new google.maps.Map(mapCanvas, {
    center: new google.maps.LatLng(-34.397, 150.644)
});

如果我没有输入地图选项,或者我输入了但没有设置有效的center,那么我会得到一个空白的地图,无法加载瓦片。

1
如果地图的高度/宽度为0,也会出现这种情况。

0

我尝试设置地图的MapTypeId,像Anurag建议的那样解决了问题:

map.setMapTypeId(google.maps.MapTypeId.TERRAIN);

-4

我看到你的代码存在一个普遍的JavaScript问题。

你的脚本可能在HTML加载之前尝试嵌入地图。

可以像这样调用函数(还有其他方法)。

<body onload="initialize()">

这不是实际问题,看下面的答案。它们突出了代码存在的问题。 - The Dark Knight
@Padrig,我实际上已经尝试过这个,但是当我这样做时,地图框甚至都不会加载。 - bencarter78

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接