【问题标题】:Google Maps v3: How to tell when an ImageMapType overlay's tiles are finished loading?Google Maps v3:如何判断 ImageMapType 叠加层的图块何时完成加载?
【发布时间】:2011-09-07 23:59:38
【问题描述】:

我正在使用 Google Maps v3 API,并且我有一个基于 ImageMapType 类的自定义叠加层。我想在加载叠加层的图块时显示某种加载指示器,但我看不到任何方法可以知道它们何时完成。

创建叠加层的代码类似于以下内容:

var myOverlay = new google.maps.ImageMapType({
    getTileUrl: myGetTileUrl,
    tileSize: new google.maps.Size(256, 256),
    isPng: true
});

myMap.overlayMapTypes.push(myOverlay);

以上工作正常,叠加成功加载;似乎地图没有发出任何事件来指示有关 ImageMapType 叠加层状态的任何信息。

我希望地图在图块加载完成时至少会发出一个“空闲”事件,但据我所知不会。

我如何知道 ImageMapType 叠加层何时完成加载?

编辑

我在 jsFiddle 上编写了一个测试用例:http://jsfiddle.net/6yvcB/ — 观察控制台输出中的“idled”一词,以查看空闲事件何时触发。请注意,当您单击按钮添加叠加层时,它永远不会触发。

还有,小猫。

【问题讨论】:

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


    【解决方案1】:

    似乎没有“开箱即用”的方式来知道 ImageMapType 覆盖何时完成加载,但感谢Google Maps API v3 Forums 上的suggestion from Martin,我能够添加我自己的自定义事件,即图层加载完成时发出。

    基本做法是:

    • 每次请求 URL 时,将该 URL 添加到待处理 URL 列表中
    • 覆盖 ImageMapType.getTile() 以便我们可以向每个 元素添加“onload”事件侦听器。
    • 当每个图像的“加载”事件触发时,从待处理 URL 列表中删除该图像。
    • 当待处理的 URL 列表为空时,发出我们的自定义“overlay-idle”事件。

    我为后代复制了以下代码,但您可以在 jsFiddle 上看到它的实际效果:http://jsfiddle.net/6yvcB/22/

    // Create a base map
    var options = {
        zoom: 3,
        center: new google.maps.LatLng(37.59, -99.13),
        mapTypeId: "terrain"
    };
    var map = new google.maps.Map($("#map")[0], options);
    
    // Listen for the map to emit "idle" events
    google.maps.event.addListener(map, "idle", function(){
        console.log("map is idle");
    });
    
    // Keep track of pending tile requests
    var pendingUrls = [];
    
    $("#btn").click(function() {
        var index = 0;   
        var urls = [ "http://placekitten.com/256/256", 
                     "http://placekitten.com/g/256/256",
                     "http://placekitten.com/255/255", 
                     "http://placekitten.com/g/255/255",
                     "http://placekitten.com/257/257", 
                     "http://placekitten.com/g/257/257" ];
    
        var overlay = new google.maps.ImageMapType({
            getTileUrl: function() { 
                var url = urls[index % urls.length];
                index++;
    
                // Add this url to our list of pending urls
                pendingUrls.push(url);
    
                // if this is our first pending tile, signal that we just became busy
                if (pendingUrls.length === 1) {
                     $(overlay).trigger("overlay-busy");   
                }
    
                return url; 
            },
            tileSize: new google.maps.Size(256, 256),
            isPng: true,
            opacity: 0.60
        });
    
        // Listen for our custom events
        $(overlay).bind("overlay-idle", function() {
            console.log("overlay is idle"); 
        });
    
        $(overlay).bind("overlay-busy", function() {
            console.log("overlay is busy"); 
        });
    
    
        // Copy the original getTile function so we can override it, 
        // but still make use of the original function
        overlay.baseGetTile = overlay.getTile;
    
        // Override getTile so we may add event listeners to know when the images load
        overlay.getTile = function(tileCoord, zoom, ownerDocument) {
    
            // Get the DOM node generated by the out-of-the-box ImageMapType
            var node = overlay.baseGetTile(tileCoord, zoom, ownerDocument);
    
            // Listen for any images within the node to finish loading
            $("img", node).one("load", function() {
    
                // Remove the image from our list of pending urls
                var index = $.inArray(this.__src__, pendingUrls);
                pendingUrls.splice(index, 1);
    
                // If the pending url list is empty, emit an event to 
                // indicate that the tiles are finished loading
                if (pendingUrls.length === 0) {
                    $(overlay).trigger("overlay-idle");
                }
            });
    
            return node;
        };
    
        map.overlayMapTypes.push(overlay);
    });
    

    【讨论】:

    • 感谢您的出色解决方案!
    • 这似乎不起作用(不再?)。即使在您的 jsfiddle 中,即使所有小猫图像都已加载,它也永远不会记录“Overlay is idle”。
    【解决方案2】:

    使用事件tilesloaded

    文档:About event tilesloaded

    【讨论】:

      【解决方案3】:

      根据@David 的回复,我创建了一个纯 Javascript 替代方案(特别是考虑到 Op 没有指定 jQuery)。

      var pendingUrls = [];
      
      function addPendingUrl(id, url)
      {
          // Add this url to our list of pending urls
          pendingUrls[id].push(url);
      
          //console.log("URL " + url + " added (" + pendingUrls[id].length + ")");
      
          // if this is our first pending tile, signal that we just became busy
          if (pendingUrls[id].length === 1) {
              console.log("overlay is busy");
          }
      }
      
      function addTileLoadListener(id, mapType, timeout)
      {
          // Initialise the sub-array for this particular id
          pendingUrls[id] = [];
      
          // Copy the original getTile function so we can override it, but still make use of the original function
          mapType.baseGetTile = mapType.getTile;
      
          // Override getTile so we may add event listeners to know when the images load
          mapType.getTile = function(tileCoord, zoom, ownerDocument)
          {
              // Get the DOM node generated by the out-of-the-box ImageMapType
              var node = mapType.baseGetTile(tileCoord, zoom, ownerDocument);
      
              //console.log("URL " + node.firstChild.__src__ + " confirmed (" + pendingUrls[id].length + ")");
      
              function removePendingImg(node, src, result)
              {
                  var index = pendingUrls[id].indexOf(src);
                  if (index == -1)
                  {
                      //console.log("URL " + src + " " + "not found" + " (" + pendingUrls[id].length + ")");
                  }
                  else
                  {
                      pendingUrls[id].splice(index, 1);
                      //console.log("URL " + src + " " + result + " (" + pendingUrls[id].length + ")");
      
                      // If the pending url list is empty, emit an event to indicate that the tiles are finished loading
                      if (pendingUrls[id].length === 0) {
                          console.log("overlay is idle");
                      }                
                  }
              }
      
              // Listen for any images within the node to finish loading
              node.getElementsByTagName("img")[0].onload = function() {
                  //console.log("URL " + node.firstChild.src + " maybe loaded (" + node.firstChild.__src__ + ")");
      
                  // Check that we have loaded the final image. We detect this because the node.src ends with what is in node.__src__
                  var str = node.firstChild.src;
                  var suffix = node.firstChild.__src__;
                  if (str.indexOf(suffix, str.length - suffix.length) !== -1)
                  {
                      removePendingImg(node, node.firstChild.__src__, "loaded");   // Remove the image from our list of pending urls
                  }
              };
      
              // Limit the wait
              var imgsrc = node.firstChild.__src__;
              setTimeout(function() {
                  if (node.firstChild)    // if the map has already changed and the image is not going to be loaded, the node is destroyed
                  {
                      //var index = pendingUrls[id].indexOf(node.firstChild.__src__);
                      //if (index != -1)
      
                      // If the image is not loaded yet (node.src changes to the same value as node.firstChild.__src__ when loaded)
                      var str = node.firstChild.src;
                      var suffix = node.firstChild.__src__;
                      if (!(str.indexOf(suffix, str.length - suffix.length) !== -1))
                      {
                          node.getElementsByTagName("img")[0].onload = null;  // Disable the event handler for this node
                          removePendingImg(node, node.firstChild.__src__, "timed out");    // Remove the image from our list of pending urls
                      }
                  }
                  else removePendingImg(node, imgsrc, "discarded");    // Remove the image from our list of pending urls
              }, timeout);
      
              return node;
          };
      }
      

      并且可以从任何 getTileUrl 函数轻松调用这些函数。

      myMapType = new google.maps.ImageMapType({
          getTileUrl: function(coord, zoom)
          {
              var url = '//a.tile.server.com/' + zoom + '/' + coord.x + '/' + coord.y + '.png';
      
              // Add this url to our list of pending urls, and enable the loading image if appropriate
              addPendingUrl("myLayer", url);
      
              return url;
          },
          tileSize: new google.maps.Size(256, 256),
          opacity: 0.5
      });
      
      // Listen for all the images having been loaded
      addTileLoadListener("myLayer", myMapType, 15000);
      

      额外功能:支持多层和超时(以防服务器运行缓慢或马虎)。

      【讨论】:

      • 我在这个版本中观察到的唯一问题是,当切片已经在缓存中时,不会触发 onload 事件。解决方法应该是在src参数之前设置onload事件(stackoverflow.com/a/12355031/1816603),但是不知道这是否兼容覆盖getTile方法的方式,因为图片src是在Maps代码中设置的。跨度>
      猜你喜欢
      • 2011-02-26
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多