如何解决“Uncaught ReferenceError: google is not defined”? (谷歌地图 API)

时间:2021-02-19 15:52:10

标签: javascript html jquery

我很难显示一个简单的标记,确实我在 Chrome 控制台中有“Uncaught ReferenceError: google is not defined”并且标记没有出现。我在论坛上到处搜索,但没有任何帮助。我真的看过每一篇文章,但总是出现这个错误并且没有添加任何标记。

我给你我的 HTML 代码

 <!DOCTYPE html>
<html lang="lv">
    <head>
        <title>SparkleHeart</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <link rel='icon' href='assets/img//Intersect.svg' type='image/x-icon' />
        <link rel="stylesheet" href="assets/css/normalize.css" />
        <link rel="stylesheet" href="assets/css/style.css" />
        
        <script
        src="https://use.fontawesome.com/releases/v5.15.2/js/all.js"
        data-auto-a11y="true"></script>
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
        <script src='assets/js/theme.js'></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha512-Rc24PGD2NTEGNYG/EMB+jcFpAltU9svgPcG/73l1/5M6is6gu3Vo1uVqyaNWf/sXfKyI0l240iwX9wpm6HE/Tg==" crossorigin="anonymous"></script>

    </head>

    <body>

  
            <main>
 
                <div>
                    
                    <!-- Drop-Down Filter Menu -->
                    <select id="type" onchange="filterMarkers(this.value);">
                    <option value="">Please select category</option>
                    <option value="Branch">Branch</option>
                    <option value="ATM">ATM</option>
                    <option value="Drive-Thru">Drive-Thru</option>
                    <!--Add more "options" for the dropdown menu-->
                    </select>
                   
                <div id="map-canvas"></div>
                </div>
             
                <script
                src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBGwz_8OxIGhS_nOIPS2F_mH1ie5WfmhZ0&map_ids=e24b393c59b842b4&callback=initMap" async defer>
                </script>
              
  
            </main>
    </body>
</html>

var gmarkers1 = [];
var markers1 = [];
var infowindow = new google.maps.InfoWindow({
    content: ''
});





// Function to init map


function initMap() {
    var center = new google.maps.LatLng(56.9496,24.1052);
    var mapOptions = {
        zoom: 14,
        center: center,
        mapId: 'e24b393c59b842b4',
    };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    for (i = 0; i < markers1.length; i++) {
        addMarker(markers1[i]);
    }
}



// Function to add markers to map


function addMarker(marker) {
    var category = marker[4];
    var title = marker[1];
    var pos = new google.maps.LatLng(marker[2], marker[3]);
    var content = marker[1];

    marker1 = new google.maps.Marker({
        title: title,
        position: pos,
        category: category,
        map: map
    });

    gmarkers1.push(marker1);

// Marker click listener (zoom in and open info window)
    google.maps.event.addListener(marker1, 'click', (function (marker1, content) {
        return function () {
            console.log('Gmarker 1 gets pushed');
            infowindow.setContent(content);
            infowindow.open(map, marker1);
            map.panTo(this.getPosition());
            map.setZoom(13);
        }
    })(marker1, content));
}


// Function to filter markers by category


filterMarkers = function (category) {
    for (i = 0; i < markers1.length; i++) {
        marker = gmarkers1[i];
        // If is same category or category not picked
        if (marker.category == category || category.length === 0) {
            marker.setVisible(true);
            
        }
        
        // if Categories don't match 
        else {
            marker.setVisible(false);
        }
    }
}

// Add markers (you can add as many as you like)
// Note, marker #5 has a lot of styling and an image in the info window. Just showing an example of what you can do with an info window.
markers1 = [
    ['0', 'Lee Blvd Branch', 56.9496, 24.1052, 'Branch'],
    ['1', 'Lee Blvd ATM', 34.613839, -98.409974, 'ATM'],
    ['2', 'Annex Branch', 34.607799, -98.396419, 'Branch'],
    ['3', 'West Branch', 34.623425, -98.468883, 'Drive-Thru'],
    ['4', 'East ATM', 34.593839, -98.409974, 'ATM'],
    ['5',  '<div style=\"font-size:12px; color:#000; \"><img id=\'popimg\' src=\'https://s3-us-west-2.amazonaws.com/s.cdpn.io/44720/paris.jpg\'  <br/><br/><strong>Address:</strong><br/>123 Happy Place<br/><br/><strong>City-State-Zip:</strong><br/>Lawton, OK. 73509<br/><br/><strong>Phone:</strong><br/>580-555-1234<br/><br/> <strong>Type:</strong><br/>(ATM)<br/><br/><strong>Monday - Friday</strong><br/>9:00 AM - 5:00 PM &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</div>"', 34.713839, -98.409974, 'ATM']
];

// Init map
initMap();

1 个答案:

答案 0 :(得分:0)

错误 google is not defined 被抛出,因为您在定义之前尝试使用 google 对象:

var infowindow = new google.maps.InfoWindow({
    content: ''
});

它是由对异步加载的 https://maps.googleapis.com/maps/api/js 的脚本调用定义的。因此,一旦加载,initMap() 函数就会运行,因为它已传递给请求:&callback=initMap 因此您不必在代码中调用 initMap

我添加了两个 console.logs 以显示 initMap 正在运行并且添加了 5 个标记。下面的代码段中显示了一条奇怪的 Script error. 消息,我不明白为什么......但它没有显示在 CodePen

#map-canvas{
  height: 500px;
}
<html lang="lv">

<head>
  <title>SparkleHeart</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <!--link rel='icon' href='assets/img//Intersect.svg' type='image/x-icon' />
        <link rel="stylesheet" href="assets/css/normalize.css" />
        <link rel="stylesheet" href="assets/css/style.css" />
        
        <script--
        src="https://use.fontawesome.com/releases/v5.15.2/js/all.js" data-auto-a11y="true"></script-->
  <script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
  <!--script src='assets/js/theme.js'></script-->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js" integrity="sha512-Rc24PGD2NTEGNYG/EMB+jcFpAltU9svgPcG/73l1/5M6is6gu3Vo1uVqyaNWf/sXfKyI0l240iwX9wpm6HE/Tg==" crossorigin="anonymous"></script>

</head>

<body>

  <main>

    <div>

      <!-- Drop-Down Filter Menu -->
      <select id="type" onchange="filterMarkers(this.value);">
        <option value="">Please select category</option>
        <option value="Branch">Branch</option>
        <option value="ATM">ATM</option>
        <option value="Drive-Thru">Drive-Thru</option>
        <!--Add more "options" for the dropdown menu-->
      </select>

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

    <script>
      var gmarkers1 = [];
      var markers1 = [];
      //var infowindow; // = new google.maps.InfoWindow({
      //    content: ''
      //});
      // Function to init map
      function initMap() {
        console.log("init map")
        
        infowindow = new google.maps.InfoWindow({content: ''});
        
        var center = new google.maps.LatLng(56.9496, 24.1052);
        var mapOptions = {
          zoom: 14,
          center: center,
          mapId: "e24b393c59b842b4"
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
        for (i = 0; i < markers1.length; i++) {
          addMarker(markers1[i]);
        }
      }
      // Function to add markers to map
      function addMarker(marker) {
        console.log("Add marker",marker)
        var category = marker[4];
        var title = marker[1];
        var pos = new google.maps.LatLng(marker[2], marker[3]);
        var content = marker[1];
        marker1 = new google.maps.Marker({
          title: title,
          position: pos,
          category: category,
          map: map
        });
        gmarkers1.push(marker1);
        // Marker click listener (zoom in and open info window)
        google.maps.event.addListener(
          marker1,
          "click",
          (function(marker1, content) {
            return function() {
              console.log("Gmarker 1 gets pushed");
              infowindow.setContent(content);
              infowindow.open(map, marker1);
              map.panTo(this.getPosition());
              map.setZoom(13);
            };
          })(marker1, content)
        );
      }
      // Function to filter markers by category
      //filterMarkers = function (category) {
      function filterMarkers(category) {
        for (i = 0; i < markers1.length; i++) {
          marker = gmarkers1[i];
          // If is same category or category not picked
          if (marker.category == category || category.length === 0) {
            marker.setVisible(true);
          }
          // if Categories don't match
          else {
            marker.setVisible(false);
          }
        }
      }
      // Add markers (you can add as many as you like)
      // Note, marker #5 has a lot of styling and an image in the info window. Just showing an example of what you can do with an info window.
      markers1 = [
        ["0", "Lee Blvd Branch", 56.9496, 24.1052, "Branch"],
        ["1", "Lee Blvd ATM", 34.613839, -98.409974, "ATM"],
        ["2", "Annex Branch", 34.607799, -98.396419, "Branch"],
        ["3", "West Branch", 34.623425, -98.468883, "Drive-Thru"],
        ["4", "East ATM", 34.593839, -98.409974, "ATM"],
        [
          "5",
          "<div style=\"font-size:12px; color:#000; \"><img id='popimg' src='https://s3-us-west-2.amazonaws.com/s.cdpn.io/44720/paris.jpg'  <br/><br/><strong>Address:</strong><br/>123 Happy Place<br/><br/><strong>City-State-Zip:</strong><br/>Lawton, OK. 73509<br/><br/><strong>Phone:</strong><br/>580-555-1234<br/><br/> <strong>Type:</strong><br/>(ATM)<br/><br/><strong>Monday - Friday</strong><br/>9:00 AM - 5:00 PM &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp</div>\"",
          34.713839,
          -98.409974,
          "ATM"
        ]
      ];
      // Init map
      //initMap();
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBGwz_8OxIGhS_nOIPS2F_mH1ie5WfmhZ0&map_ids=e24b393c59b842b4&callback=initMap" async defer>
    </script>

  </main>
</body>

</html>