Google 仅在页面刷新后加载地图

Google Maps loading only after page refresh

出于某种原因,我的 google 地图仅在我刷新页面后加载。我已经尝试了一些修复,但它们对我不起作用。

我已经添加了

    $(document).ready(function() {
      initMap();
});

    $(document).bind("projectLoadComplete", initMap);

我的代码,但它没有解决问题。

有些人也使用 google.maps.event.addDomListener(window, 'load', initialize); 而不是 $(document).ready(function() {initMap();}); 但后来我收到错误:“Google 未定义”。

这是没有 css 的完整 HTML 代码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Marker</title>
  <link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script type="text/javascript">
    function initMap() {

      window.onmessage = (event) => {
        if (event.data) {

          const map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(48.68933623258264, 11.05938929396435),
            zoom: 5,
            streetViewControl: false,
            fullscreenControl: true,
            zoomControl: true,
          });
          const input = document.getElementById("pac-input");
          const autocomplete = new google.maps.places.Autocomplete(input);
          autocomplete.setComponentRestrictions({
            country: ["de", "ch", "at", "it", "lie"]
          });
          autocomplete.bindTo("bounds", map);

          var markerIcon = {
            url: "https://static.wixstatic.com/media/c4g8dl_c2fd4dfd9ce72ede7acb9e44~mv2.png",
            size: new google.maps.Size(22, 35),
            origin: new google.maps.Point(0, 0),
            scaledSize: new google.maps.Size(22, 35)
          };

          autocomplete.setFields(["place_id", "formatted_address", "geometry", "name"]);
          const infowindow = new google.maps.InfoWindow();
          const infowindowContent = document.getElementById("infowindow-content");
          infowindow.setContent(infowindowContent);

          const marker = new google.maps.Marker({
            map: map,
            icon: markerIcon
          });
          marker.addListener("click", () => {
            infowindow.open(map, marker);
          });
          autocomplete.addListener("place_changed", () => {
            infowindow.close();
            const place = autocomplete.getPlace();

            if (!place.geometry || !place.geometry.location) {
              return;
            }

            if (place.geometry.viewport) {
              map.fitBounds(place.geometry.viewport);
            } else {
              map.setCenter(place.geometry.location);
              map.setZoom(17);
            }

            marker.setPlace({
              placeId: place.place_id,
              location: place.geometry.location,
            });
            marker.setVisible(true);
            infowindowContent.children.namedItem("place-name").textContent = place.name;
            infowindowContent.children.namedItem("place-address").textContent = place.formatted_address;
            infowindow.open(map, marker);

            window.parent.postMessage([place.name, place.formatted_address, place.geometry.location.lat(), place.geometry.location.lng()], "*");
          });
        }
      }
    }

    function ready() {
      window.parent.postMessage({
        "type": "ready"
      }, "*");
    }

    $(document).ready(function() {
      initMap();
    });
    $(document).bind("projectLoadComplete", initMap);
  </script>
</head>

<body onload="ready()">

  <div id="input">
    <input id="pac-input" class="controls" type="text" placeholder="adress">
  </div>

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

  <div id="infowindow-content">
    <span id="place-name" class="title"></span><br />
    <span id="place-address"></span><br />
  </div>

  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>
</body>

</html>

编辑:如果我在新选项卡中打开带有我的地图的页面,地图正在加载。如果我在同一个选项卡中打开页面,就会发生错误。 也许我的网站没有触发我的 iFrame 的完整代码。

我解决了这个问题。问题是 window.onmessage = (event) => {。 我认为地图无法加载,因为回调在地图收到 onmessage 事件之前运行。

我使用了我创建的另一个地图中的代码,所以我删除了 onmessage 部分,因为我只需要将一些数据发送到我的网站,而不是从我的网站发送到我的 html。

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Marker</title>
  <link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script type="text/javascript">
    function initMap() {

      const map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(48.68933623258264, 11.05938929396435),
        zoom: 5,
        streetViewControl: false,
        fullscreenControl: true,
        zoomControl: true,
      });

      const input = document.getElementById("pac-input");
      const autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.setComponentRestrictions({
        country: ["de", "ch", "at", "it", "lie"]
      });
      autocomplete.bindTo("bounds", map);

      var markerIcon = {
        url: "https://static.wixstatic.com/media/e6dc2fd4dfd9ce72ede7acb9e44~mv2.png",
        size: new google.maps.Size(22, 35),
        origin: new google.maps.Point(0, 0),
        scaledSize: new google.maps.Size(22, 35)
      };

      autocomplete.setFields(["place_id", "formatted_address", "geometry", "name"]);
      const infowindow = new google.maps.InfoWindow();
      const infowindowContent = document.getElementById("infowindow-content");
      infowindow.setContent(infowindowContent);

      const marker = new google.maps.Marker({
        map: map,
        icon: markerIcon
      });
      marker.addListener("click", () => {
        infowindow.open(map, marker);
      });
      autocomplete.addListener("place_changed", () => {
        infowindow.close();
        const place = autocomplete.getPlace();

        if (!place.geometry || !place.geometry.location) {
          return;
        }

        if (place.geometry.viewport) {
          map.fitBounds(place.geometry.viewport);
        } else {
          map.setCenter(place.geometry.location);
          map.setZoom(17);
        }

        marker.setPlace({
          placeId: place.place_id,
          location: place.geometry.location,
        });
        marker.setVisible(true);
        infowindowContent.children.namedItem("place-name").textContent = place.name;
        infowindowContent.children.namedItem("place-address").textContent = place.formatted_address;
        infowindow.open(map, marker);

        window.parent.postMessage([place.name, place.formatted_address, place.geometry.location.lat(), place.geometry.location.lng()], "*");
      });
    }
  </script>
</head>

<body onload="initMap()">

  <div id="input">
    <input id="pac-input" class="controls" type="text" placeholder="add adress">
  </div>

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

  <div id="infowindow-content">
    <span id="place-name" class="title"></span><br />
    <span id="place-address"></span><br />
  </div>

  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=MY_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>
</body>

</html>