为什么我无法加载谷歌地图?

时间:2017-05-23 11:19:50

标签: javascript google-maps

我是编程和尝试学习的新手。对于一个项目想要加载谷歌地图,但我一直在尝试从几个小时,但似乎无法加载谷歌地图,但我没有在控制台中看到任何JavaScript错误。任何人都可以指出我正在做的错误

<!DOCTYPE html>
<html>
<head>
    <title>BART</title>
    <style>
    body
    {
        height: 100%;
    }
    #map
    {
        height: 80%;
        width: 60%;
    }   
    </style>
    <script src = "https://maps.googleapis.com/maps/api/js?key=mykey</script>
    <script>
        var map ;


        //function to initialize map
        var initialize = function()
            {
            var mapOptions = {
                center :{lat: 37.775362, lng: -122.417564},
                zoom : 12,
                mapTypeId : google.maps.MapTypeId.ROADMAP
                };

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


            window.onload = initialize; 
    </script>

</head>
<body>
    <div id ="map">
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您应该将CSS添加为

#map {
  height: 400px;
  width: 400px;
}

<!DOCTYPE html>
<html>

<head>
  <title>BART</title>
  <style>
    body {
      height: 100%;
    }
    
    #map {
      height: 400px;
      width: 400px;
    }
  </style>
  <script src="https://maps.googleapis.com/maps/api/js?"></script>
  <script>
    var map;


    //function to initialize map
    var initialize = function() {
      var mapOptions = {
        center: {
          lat: 37.775362,
          lng: -122.417564
        },
        zoom: 12,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };

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


    window.onload = initialize;
  </script>

</head>

<body>
  <div id="map">
  </div>
</body>

</html>

答案 1 :(得分:0)

请使用Google地图文档中提供的代码。

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 8
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    async defer></script>
  </body>
</html>