javascript setInterval不起作用?

时间:2011-10-10 17:20:53

标签: javascript google-maps-api-3

我正在尝试使用“setInterval”来重新加载包含嵌入式googlemaps的网页。

当我使用时:

var marker = createMarker (point, id);

页面运行正常(一次)。但是当我尝试:

var marker = setInterval (function () {createMarker (point, id);}, 5000);

自动刷新页面,发生以下错误:

main.js:686Uncaught TypeError: Object 8 has no method 'initialize

有什么想法吗?提前谢谢!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <!--<META HTTP-EQUIV="refresh" CONTENT="15">-->
    <title>Position</title>

    <script src="http://maps.google.com/maps?file=api&v=2&key="
            type="text/javascript"></script>
    <script type="text/javascript" >
    //<![CDATA[

    var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
                new google.maps.Size(32, 32),
                new google.maps.Point(0, 0),
                new google.maps.Point(16, 32)
            );

    function load() {
      if (GBrowserIsCompatible()) {
        //create map and center it
        var map = new GMap2(document.getElementById("map"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());

        GDownloadUrl("gen_xml.php", function(data) {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var id = markers[i].getAttribute("id");
            var point = new GLatLng(
                    parseFloat(markers[i].getAttribute("latitude")),
                    parseFloat(markers[i].getAttribute("longitude"))
            );
            //var marker = createMarker(point, id);
            var marker = setInterval(function(){createMarker(point, id);},5000);
            map.addOverlay(marker);
            map.setCenter(point,17);

          }
        });

      }
    }

    function createMarker(point, id) {
      var marker = new GMarker(point, icon);
      var html = "<b>" + id + "</b> <br/>" + point;
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }

    //]]>
  </script>
  </head>

  <body onload="load()" onunload="GUnload()">
  <center>
    <div id="map" style="width: 800px; height: 600px"></div>
  </center>
  </body>
</html>

1 个答案:

答案 0 :(得分:3)

setInterval返回一个整数,而不是createMarker()返回的值。使用createMarker 回调中setInterval 返回的值。

setInterval(function ()
{
    var marker = createMarker(point, id);
    map.addOverlay(marker);
    map.setCenter(point, 17);
}, 5000);

您可能也会看到classic JS function-in-a-loop problem