将 Google 地图放在 col div 中

Placing Google Map inside a col div

我正在尝试创建一个由两部分并排组成的商店定位器,一个用于国家和位置列表(左),另一个用于 Google 地图(使用 Google地图JavascriptAPI).

我正在使用 Bootstrap 创建布局,但是,我遇到了一个奇怪的问题,即地图 div 如果放置在任何父级 div 中则不会显示,或者section(如果在body标签下,则正常)。

这是我正在使用的代码;

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Noble Panacea | Store Locator</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  </head>
  <body>
    <section class="mapSection">
      <div class="container">
        <div class="row">
          <!-- List Div
          some content 
          <div class="col-md-3 listHalf">
            <h1>SELECT COUNTRY</h1>
            <div class="countryCard">....
          -->
          
          <!-- the map div placed inside a bootstrap col-->
           <div class="col-md-9">
            <h1>Map</h1>
            <div id="map"></div>
          </div>
          
        </div>
      </div>
    </section>

上面只显示了列表部分,而根本没有加载地图。

如果我将 id=map div 移到 col div 之外,它将正常显示。

启动地图的API脚本如下:

    <!-- Main App -->
    <script>

      var map;
      var markers = [];
      var infoWindow;

      // Map Styling
      const mapStyle = [{
          'featureType': 'administrative',
          'elementType': 'all',
          'stylers': [{
            'visibility': 'on',
          },
          {
            'lightness': 33,
          },
          ],
        },
        {
          'featureType': 'landscape',
          'elementType': 'all',
          'stylers': [{
            'color': '#f2e5d4',
          }],
        },
        {
          'featureType': 'poi.park',
          'elementType': 'geometry',
          'stylers': [{
            'color': '#c5dac6',
          }],
        },
        {
          'featureType': 'poi.park',
          'elementType': 'labels',
          'stylers': [{
            'visibility': 'on',
          },
          {
            'lightness': 20,
          },
          ],
        },
        {
          'featureType': 'road',
          'elementType': 'all',
          'stylers': [{
            'lightness': 20,
          }],
        },
        {
          'featureType': 'road.highway',
          'elementType': 'geometry',
          'stylers': [{
            'color': '#c5c6c6',
          }],
        },
        {
          'featureType': 'road.arterial',
          'elementType': 'geometry',
          'stylers': [{
            'color': '#e4d7c6',
          }],
        },
        {
          'featureType': 'road.local',
          'elementType': 'geometry',
          'stylers': [{
            'color': '#fbfaf7',
          }],
        },
        {
          'featureType': 'water',
          'elementType': 'all',
          'stylers': [{
            'visibility': 'on',
          },
          {
            'color': '#acbcc9',
          },
          ],
        },
        ];


      function initMap() {

          // Create the map.
          var centerMap = {lat: 52.632469, lng: -1.689423};

          const map = new google.maps.Map(document.getElementById("map"), {
            center: centerMap,
            zoom: 8,
            styles: mapStyle,
          });


           // Load the stores GeoJSON onto the map.
          map.data.loadGeoJson('store-data.js', {idPropertyName: 'storeid'});
          const apiKey = 'KEYYYYYY';
          const infoWindow = new google.maps.InfoWindow({maxWidth:350});


          // Define the custom marker icons, using the store's "category".
          map.data.setStyle((feature) => {
            return {
              animation: google.maps.Animation.DROP,
              icon: {
                url: `marker.png`,
                scaledSize: new google.maps.Size(40, 50),
              },
            };
          });

          map.data.addListener('mouseover', function(event) {
            // Bounce animation on hover           
            map.data.overrideStyle(event.feature, {animation: google.maps.Animation.BOUNCE});
          });


          map.data.addListener('click', function(event) {
            // Show the information for a store when its marker is hovered.
            const category = event.feature.getProperty('category');
            const name = event.feature.getProperty('name');
            const description = event.feature.getProperty('description');
            const hours = event.feature.getProperty('hours');
            const phone = event.feature.getProperty('phone');
            const logo = event.feature.getProperty('logo');
            const position = event.feature.getGeometry().get();
            const content = `
            <div class="infoBox">
              <img class="logo" src="/${logo}">
              <p>${description}</p>
              <p><b>Open:</b> ${hours}<br/><b>Phone:</b> ${phone}</p>
              <p><img src="/Sample.jpg"></p>
            </div>
            `;

            infoWindow.setContent(content);
            infoWindow.setPosition(position);
            infoWindow.setOptions({pixelOffset: new google.maps.Size(0, -30)});
            infoWindow.open(map);
          });

          map.data.addListener('mouseout', function(event) {
            // remove animation on mouseout  
            map.data.overrideStyle(event.feature, {animation: "none" });
          });

          };

    </script>

    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=KEYYYYY&callback=initMap">
    </script>

有没有办法显示 google 映射在 div 内,并使其始终覆盖它的整个宽度?

相关问题:

  • google maps refreshing grey

来自第一个问题:

make sure the div where the map is displayed has a valid size, if it is hidden, it will have zero size and you will need to display the div before it will have a valid size. If it is sized using percentages, make sure that all of its parent elements either have a percent size or a specific size (see Mike Williams' Google Maps API v2 tutorial on the subject for details).

您的地图没有尺寸。

显示地图的概念代码片段证明:
(您可能需要调整 CSS 以使您的布局正常工作)

var map;
var markers = [];
var infoWindow;

// Map Styling
const mapStyle = [{
    'featureType': 'administrative',
    'elementType': 'all',
    'stylers': [{
        'visibility': 'on',
      },
      {
        'lightness': 33,
      },
    ],
  },
  {
    'featureType': 'landscape',
    'elementType': 'all',
    'stylers': [{
      'color': '#f2e5d4',
    }],
  },
  {
    'featureType': 'poi.park',
    'elementType': 'geometry',
    'stylers': [{
      'color': '#c5dac6',
    }],
  },
  {
    'featureType': 'poi.park',
    'elementType': 'labels',
    'stylers': [{
        'visibility': 'on',
      },
      {
        'lightness': 20,
      },
    ],
  },
  {
    'featureType': 'road',
    'elementType': 'all',
    'stylers': [{
      'lightness': 20,
    }],
  },
  {
    'featureType': 'road.highway',
    'elementType': 'geometry',
    'stylers': [{
      'color': '#c5c6c6',
    }],
  },
  {
    'featureType': 'road.arterial',
    'elementType': 'geometry',
    'stylers': [{
      'color': '#e4d7c6',
    }],
  },
  {
    'featureType': 'road.local',
    'elementType': 'geometry',
    'stylers': [{
      'color': '#fbfaf7',
    }],
  },
  {
    'featureType': 'water',
    'elementType': 'all',
    'stylers': [{
        'visibility': 'on',
      },
      {
        'color': '#acbcc9',
      },
    ],
  },
];


function initMap() {

  // Create the map.
  var centerMap = {
    lat: 52.632469,
    lng: -1.689423
  };

  const map = new google.maps.Map(document.getElementById("map"), {
    center: centerMap,
    zoom: 8,
    styles: mapStyle,
  });


  // Load the stores GeoJSON onto the map.
  map.data.loadGeoJson('store-data.js', {
    idPropertyName: 'storeid'
  });
  const apiKey = 'KEYYYYYY';
  const infoWindow = new google.maps.InfoWindow({
    maxWidth: 350
  });


  // Define the custom marker icons, using the store's "category".
  map.data.setStyle((feature) => {
    return {
      animation: google.maps.Animation.DROP,
      icon: {
        url: `marker.png`,
        scaledSize: new google.maps.Size(40, 50),
      },
    };
  });

  map.data.addListener('mouseover', function(event) {
    // Bounce animation on hover           
    map.data.overrideStyle(event.feature, {
      animation: google.maps.Animation.BOUNCE
    });
  });


  map.data.addListener('click', function(event) {
    // Show the information for a store when its marker is hovered.
    const category = event.feature.getProperty('category');
    const name = event.feature.getProperty('name');
    const description = event.feature.getProperty('description');
    const hours = event.feature.getProperty('hours');
    const phone = event.feature.getProperty('phone');
    const logo = event.feature.getProperty('logo');
    const position = event.feature.getGeometry().get();
    const content = '<div class="infoBox">' +
      '<img class="logo" src="/${logo}">' +
      '<p>${description}</p>' +
      '<p><b>Open:</b> ${hours}<br/><b>Phone:</b> ${phone}</p>' +
      '<p><img src="/Sample.jpg"></p>' +
      '</div>';

    infoWindow.setContent(content);
    infoWindow.setPosition(position);
    infoWindow.setOptions({
      pixelOffset: new google.maps.Size(0, -30)
    });
    infoWindow.open(map);
  });

  map.data.addListener('mouseout', function(event) {
    // remove animation on mouseout  
    map.data.overrideStyle(event.feature, {
      animation: "none"
    });
  });

};
/* 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;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Noble Panacea | Store Locator</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
  <section class="mapSection" style="height:100%">
    <div class="container" style="height:100%">
      <div class="row" style="height:100%">
        <!-- List Div
          some content 
          <div class="col-md-3 listHalf">
            <h1>SELECT COUNTRY</h1>
            <div class="countryCard">....
          -->

        <!-- the map div placed inside a bootstrap col-->
        <div class="col-md-9" style="height:100%">
          <h1>Map</h1>
          <div id="map"></div>
        </div>

      </div>
    </div>
  </section>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
  </script>
</body>

</html>