Custom Google Map won't show in div element

北战南征 提交于 2020-01-25 09:49:26

问题


I'm trying to customize google map but I have a small problem.

Here is the css code:

#map-canvas {
    width: 100%;
    height: 500px;
}

and the js code:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
    function initialize() {
      var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
      var mapOptions = {
        zoom: 4,
        center: myLatlng
      }
      var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

      var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: 'Hello World!'
      });
    }

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

And this is how I initialize the map in html. This example actually works.

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

But when I trying to put my map into some div e.g:

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

It doesn't work. How to fix that ?

/// EDIT Please put this into example.html and try to run. Nothing happens for me.

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <style>
      html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
        function initialize() {
          var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
          var mapOptions = {
            zoom: 4,
            center: myLatlng
          }
          var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

          var marker = new google.maps.Marker({
              position: myLatlng,
              map: map,
              title: 'Hello World!'
          });
        }

        google.maps.event.addDomListener(window, 'load', initialize);
    </script>
</head>

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

回答1:


Your parent div should have height and width defined.

<body>
  <div style="height:100%; width:100%;">
    <div id="map-canvas"></div>
  </div>
</body>

Try This.

For more detail:

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag




回答2:


Nothing seems wrong in your code ,it works fine just seprated css.I have checked and tested.

DEMO



来源:https://stackoverflow.com/questions/23469925/custom-google-map-wont-show-in-div-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!