关闭InfoWindow时出错

时间:2017-03-31 11:53:46

标签: javascript google-maps google-maps-api-3 google-maps-markers

我想关闭之前的infoWindow,因为我打开一个新的,但是我收到了错误:

Uncaught TypeError: Cannot read property 'setContent' of null

对我来说,似乎全局变量infoWindow未被重新定义为InfoWindow()函数中的initMap()对象。我已经尝试了三种不同的方法,但我得到了同样的错误。

知道怎么解决吗?



<script>
      var map;
      var infoWindow;
      //Create personalized marker
      function createMarker(point,info) {
        var marker = new google.maps.Marker(markerOpts);
        //var infoWindowOpts = { content: info };
        //var infoWindow = new google.maps.InfoWindow(infoWindowOpts);

        google.maps.event.addListener(marker, 'click', function() {
          infoWindow.close();
          infoWindow.setContent(info);
          infoWindow.open(map, marker); 
        });
      }

      //Function to initialize the map
      function initMap() {
        //Infowindow
        var infoWindow = new google.maps.InfoWindow({
                content: "Loading..."
            });
        
        var mapCenterCoords = new google.maps.LatLng(40.787955, -78.010607);

        var mapOptions = {
          center: mapCenterCoords,
          zoom: 9,
          streetViewControl: false,
          //styles: stylesArray
        }
        
        //Map definition
        map = new google.maps.Map(document.getElementById('map'), mapOptions);
       
        //Markers coordinates
        var mark0coord = new google.maps.LatLng(40.681801, -77.807969);
        var mark1coord = new google.maps.LatLng(40.521187, -79.116672);
        var mark2coord = new google.maps.LatLng(40.223754, -78.587242);
        var mark3coord = new google.maps.LatLng(41.187436, -77.079259);
        //Markers initialization
        var marker0 = createMarker(mark0coord, "<b>Nittanytown</b></br>Population: 85000");
        var marker1 = createMarker(mark1coord, "<b>Whitney</b></br>Population: 55600");
        var marker2 = createMarker(mark2coord, "<b>Geyserville</b></br>Population: 35050");
        var marker3 = createMarker(mark3coord, "<b>Driggs</b></br>Population: 17580");
      }
</script>
    <!--Google API call-->
    <script async defer src="https://maps.googleapis.com/maps/api/js?key=XXX&callback=initMap"></script>
&#13;
<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <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: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>

  <body>
    <div id="map"></div>
  </body>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案