简体   繁体   中英

Google map API v3 - Multiple markers with infowindows not rendering

I'm new to coding and APIs in general, and using another tutorial I've managed to get a map with multiple markers and infowindows.

The map renders perfectly when previewed from a local source, but displays a blank space when uploaded to a hosting site.

Would anyone be able to give any insight on what might be wrong? I've included my code below.

<!DOCTYPE html>
<html> 
<head> 
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta content="text/html">
  <meta charset=UTF-8"> 

  <title>Google Maps Multiple Markers</title> 
  <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: 400px;
    width: 600px;
        margin: 0;
        padding: 0;
      }
    </style>

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

  <script type="text/javascript">
    var locations = [
      ['<h3>Bay of Islands</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -35.165034, 174.162854, 5],
      ['<h3>Whangarei</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -35.696121, 174.300132, 4],
      ['<h3>Mangawhai Heads</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.113032, 174.559536, 3],
      ['<h3>Auckland Hussies</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.852924, 174.750234, 2],
      ['<h3>Auckland</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.868273, 174.711450, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: new google.maps.LatLng(-40.9006, 174.8860),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    var markers = new Array();

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      markers.push(marker);

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

    function AutoCenter() {
      //  Create a new viewpoint bound
      var bounds = new google.maps.LatLngBounds();
      //  Go through each...
      $.each(markers, function (index, marker) {
      bounds.extend(marker.position);
      });
      //  Fit these bounds to the map
      map.fitBounds(bounds);
    }
    AutoCenter();

  </script> 

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

</body>
</html>

I get two javascript errors with your page (locally):

  • Uncaught ReferenceError: google is not defined
  • "initMap is not a function"

The first is because you are using async defer and callback=initMap in your script load (loading the script asynchronously)

The second because you have no initMap function.

If you load the script synchronously (remove the async defer and callback parameter), that solves both issues (although you may want to investigate why Google recommends asynchronously loading scripts and not does that in all their examples).

To do that change:

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

To:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
</script>

And move the script include to the <head> of the document.

Once I do that I get another javascript error:

Uncaught ReferenceError: $ is not defined

(because you aren't including JQuery, to fix that include <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> in the head of the document as well)

link to working page

updated code

<!DOCTYPE html>
<html> 
<head> 
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta content="text/html">
  <meta charset=UTF-8"> 

  <title>Google Maps Multiple Markers</title> 
  <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: 400px;
    width: 600px;
        margin: 0;
        padding: 0;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCxitB5jQcw7weQdg9MqBRfxr6mj81wT7I"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

  <script type="text/javascript">
    var locations = [
      ['<h3>Bay of Islands</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -35.165034, 174.162854, 5],
      ['<h3>Whangarei</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -35.696121, 174.300132, 4],
      ['<h3>Mangawhai Heads</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.113032, 174.559536, 3],
      ['<h3>Auckland Hussies</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.852924, 174.750234, 2],
      ['<h3>Auckland</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.868273, 174.711450, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 8,
      center: new google.maps.LatLng(-40.9006, 174.8860),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    var markers = new Array();

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      markers.push(marker);

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }

    function AutoCenter() {
      //  Create a new viewpoint bound
      var bounds = new google.maps.LatLngBounds();
      //  Go through each...
      $.each(markers, function (index, marker) {
      bounds.extend(marker.position);
      });
      //  Fit these bounds to the map
      map.fitBounds(bounds);
    }
    AutoCenter();

  </script> 

</body>
</html>

The problem, I believe, was that the code references an initMap callback function which plainly does not exist within the code. The callback is intended to run once all the necessary libraries have been downloaded so the modified code below should help. I also tweaked the AutoCenter function as it generated an error regarding $ being undefined - generally this is a jQuery method but no jQuery code / libraries in the above page sample.

<!DOCTYPE html>
<html> 
    <head> 
      <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
      <meta content="text/html">
      <meta charset=UTF-8">
      <title>Google Maps Multiple Markers</title> 
      <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: 400px;
        width: 600px;
            margin: 0;
            padding: 0;
          }
        </style>
    </head> 
    <body>
      <div id="map"></div>
      <script type="text/javascript">
        var locations = [
          ['<h3>Bay of Islands</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -35.165034, 174.162854, 5],
          ['<h3>Whangarei</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -35.696121, 174.300132, 4],
          ['<h3>Mangawhai Heads</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.113032, 174.559536, 3],
          ['<h3>Auckland Hussies</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.852924, 174.750234, 2],
          ['<h3>Auckland</h3>' +
            '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>', -36.868273, 174.711450, 1]
        ];

        function initMap(){
            var AutoCenter=function() {
                var bounds = new google.maps.LatLngBounds();
                markers.forEach(function(mkr){
                    bounds.extend(mkr.position);
                });
                map.fitBounds(bounds);
            }

            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 8,
              center: new google.maps.LatLng(-40.9006, 174.8860),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var infowindow = new google.maps.InfoWindow();

            var marker, i;
            var markers = [];

            for (i = 0; i < locations.length; i++) {  
              marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[i][1], locations[i][2]),
                content:locations[i][0],
                map: map
              });
              markers.push( marker );

              google.maps.event.addListener( marker, 'click', function(event) {
                  infowindow.setContent( this.content );
                  infowindow.open( map, this );
              }.bind( marker ) );
            }
            AutoCenter();
        }
      </script>
      <script async defer src="//maps.googleapis.com/maps/api/js?key=AIzaSyD3weurNK33fOlKCfokaTQWz6NKN7z8nT4&callback=initMap"></script>
    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM