2017-04-05 51 views
0

我正在尝试为ol3添加一个备份路径。我想测试errorload事件,如果源URL由“http”开头。 如果“是”:用自定义图块替换此图块。 如果“否”:由一个又一个改变这种瓷砖的来源网址,然后重试OL3添加备份网址

我想我需要使用类似的东西:

layerTile.getSource().setUrl('file:///local/{z}/{x}/{y}.jpg'); 
var errorTilePath='https://image.noelshack.com/fichiers/2017/14/1491403614-errortile.png'; 
var serverBackup='http://otile1.mqcdn.com/tiles/1.0.0/map/'; 
layerTile.getSource().setTileLoadFunction((function() { 
    var tileLoadFn = layerTile.getSource().getTileLoadFunction(); 
    return function(tile, src) { 
    var image = tile.getImage(); 
    image.onload = function() {console.log('Tile ok : ' + src); }; 
    image.onerror = function() { 
     console.log('Tile error : ' + src); 
     console.log(tile); 
     if (src.substr(0,4)!='http') { 
      var tmp=src.split('/').reverse(); 
      var serverBackupPath=serverBackup+tmp[2]+'/'+tmp[1]+'/'+tmp[0].split('.')[0]+'.png'; 
      console.log("Second url : " + serverBackupPath) 
      src=serverBackupPath; 
      tile.getImage().src=src; 
      var image = tile.getImage(); 
      image.onload = function() {console.log('Tile backup ok : ' + src);}; 
      image.onerror = function() {console.log('Tile backup error : ' + src); src=errorTilePath; tile.getImage().src=src; tileLoadFn(tile, src);} 
     } else { 
      console.log('Custom tile : '); 
      src=errorTilePath; 
      tile.getImage().src=src; 
     } 
     tileLoadFn(tile, src); 
    }; 
    tileLoadFn(tile, src); 
    }; 
})()); 

就这样,我可以看到备份瓷砖是下载但在地图上不可见。

证明,我误解了一些东西。

如果有人能帮助我,请提前致谢。

+0

我在期待的结果上取得成功,但我不确定表现。 – Slayes

回答

0

Oups,无代码我的答案为空。

layerTile.getSource().setUrl('file:///local/{z}/{x}/{y}.jpg'); 
var serverBackup='https://{a-c}.tile.openstreetmap.org/'; 
var errorTilePath=urlBase+'css/images/error.png'; 
layerTile.getSource().setTileLoadFunction((function() { 
    return function(tile, src) { 
    if (UrlExists(src)) { 
     tile.getImage().src=src; 
    } else { 
     if (src.substr(0,4)=='file') { 
      var tmp=src.split('/').reverse(); 
      src='https://'+['a', 'b', 'c'].sort(function() {return 0.5 - Math.random()})[0]+'.tile.openstreetmap.org/'+tmp[2]+'/'+tmp[1]+'/'+tmp[0].split('.')[0]+'.png'; 
      if (UrlExists(src)) { 
       tile.getImage().src=src; 
      } else { 
       tile.getImage().src=errorTilePath; 
      } 
     } else { 
      tile.getImage().src=errorTilePath; 
     } 
    } 
    }; 
})()); 

function UrlExists(url){ 
    try { 
     var http = new XMLHttpRequest(); 
     http.open('HEAD', url, false); 
     http.send(); 
     return http.status==200||http.status==403; 
    } catch(err){return false;} 
}