如何访问已加载的地图图块的源路径

时间:2016-02-16 15:39:28

标签: javascript leaflet

我有一个本地地图服务器,它在浏览器中呈现一个mbtiles文件,我正在尝试访问它生成的源文件并加载到文档中。

到目前为止,我已经能够使用document.querySelectordocument.getElementsByClassName()方法获取相应的HTMLcollection:

var collection = 
  document.querySelector(".featured")
  .getElementsByClassName("leaflet-tile");

console.log(collection);

我在Firebug上获得以下日志:

0 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
1 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
2 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
3 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
4 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
5 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
6 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
7 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
8 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
9 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
10 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
11 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
12 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1540.png
13 img.leaflet-tile.leaflet-tile-loaded ./tiles/b...1541.png
length 14
__proto__ HTMLCollection { item=item(),  namedItem=namedItem()}

我尝试了一切我记得要抓住png文件的路径。例如:

var array = [];

for (var i = 0; i < collection.length; i++) {
    array.push([
        collection[i]
]);
    console.log(collection[i]);
}

console.log("lenght of collection is: " + collection.length);
console.dir("array is: " + array);

在我的控制台上,我得到以下内容:

lenght of collection is: 0
array is: undefined

我的阵列上的零长度没有任何东西。很明显,我在迭代中做错了什么,但我无法弄清楚。我在这里缺少什么?提前谢谢!



服务器端我正在使用PHP Tileserver。这是我实例化地图对象的方式:

$(document).ready(function () {

    window.map = new L.map('map', {
        zoomControl: false,
    })
        .setView([40.6420, -73.7854], 12);

    var mapTiles = './tiles/bojb/{z}/{x}/{y}.png';

    L.tileLayer(
        mapTiles, {
            maxZoom: 16,
            minZoom: 12
        }).addTo(map);

1 个答案:

答案 0 :(得分:1)

您可以使用tileload触发的tileunloadL.TileLayer个事件:

Tileload:

  

当瓷砖加载时触发。

http://leafletjs.com/reference.html#tilelayer-tileload

Tileunload:

  

删除磁贴时触发(例如,当您启用unloadInvisibleTiles时)。

http://leafletjs.com/reference.html#tilelayer-tileunload

var tilelayer = new L.TileLayer('//{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
    'attribution': '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
});

var tilesloaded = [];

tilelayer.on('tileload', function (e) {
    if (tilesloaded.indexOf(e.url) === -1) {
        tilesloaded.push(e.url);
    }
});

tilelayer.on('tileunload', function (e) {
    var index = tilesloaded.indexOf(e.tile.src);
    tilesloaded.splice(index, 1);
});

现在tilesloaded数组将始终包含tilelayer当前加载的tile的精确表示。

这是关于Plunker的一个工作示例:http://plnkr.co/edit/mKOFDzEmVp9111Pr0tfb?p=preview