2017-04-05 109 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;} 
}