如何在 Leaflet 中为磁贴请求添加自定义授权 Header

How to add custom Authorization Header for tile requests in Leaflet

我正在使用 Leaflet.VectorGrid plugin to load pbf vector tiles on a leaflet map. The API that I retrieve the vector tiles requires an authorization header to be passed. In Mapbox GL js this can be resolved by using the transformRequest 选项。示例:

var baseLayer = L.mapboxGL({
    accessToken: token,
    style: 'myStyle',
    transformRequest: (url, resourceType)=> {
        if(resourceType == 'Tile' && url.startsWith(TILE_SERVER_HOST)) {
            return {
                url: url,
                headers: { 'Authorization': 'Basic ' + key }
            };
        }
    }
}).addTo(leafletMap);

我怎样才能在 Leaflet 中做类似的事情来绕过我收到的 401 授权消息?

参考插件中的向量层构造函数:

var vectorTileOptions = {
    rendererFactory: L.canvas.tile
};

var pbfLayer = L.vectorGrid.protobuf(vectorTileUrl, VectorTileOptions).addTo(leafletMap);

这个Github问题https://github.com/Leaflet/Leaflet.VectorGrid/issues/89 describes a fetchOptions attribute you can pass when instantiating your layer that will be used as fetch options to retrieve the tiles

你应该可以做到

var vectorTileOptions = {
    rendererFactory: L.canvas.tile,
    fetchOptions: {
        headers: { 
            Authorization: 'Basic ' + key
        }
    }
};

var pbfLayer = L.vectorGrid.protobuf(vectorTileUrl, VectorTileOptions).addTo(leafletMap);