Ulyanca Ulyanca - 4 months ago 32
Javascript Question

How to add Authorization header in getTileUrl for ImageMapType Javascript

I would like to access some Custom Map Tiles hosted on the different host who need a user / pass, when creating a TileOverlay for Google Maps API.

So this is my current code Javascript:

var carte = new google.maps.ImageMapType({
getTileUrl: function (tileCoord, zoom) {
var url = "http://host.com/" + (zoom + 1) + "/" + (tileCoord.x + 1) + ":" + (tileCoord.y + 1) + "/tile.png";
return url;
},
tileSize: new google.maps.Size(256, 256),
minZoom: 8,
opacity: 0.6
});
map.overlayMapTypes.push(carte);


Since the connection returns 401 Anauthorized, I can't access the tiles. How could I pass Authorization header in Javascript/Jquery to let the url know I am authorized to access those tiles?

I'm searching a solution like this, but in Javascript : Adding an Authorization header in getTileUrl for Maps Tile Android

Answer

I've found a solution by impementing the proxy. Here is the code implemeted :

var carte = new google.maps.ImageMapType({
        getTileUrl: function (tileCoord, zoom) {
            return 'http://myhost/myController/getTile?url=http://externe_url/' + (zoom + 1) + "/" + (tileCoord.x + 1) + ":" + (tileCoord.y + 1) + "/tile.png";
        }, 
        tileSize: new google.maps.Size(256, 256),  
        minZoom: 8,  
        opacity: 0.6
    });

Code of my controller :

def getTile() {
def result
try {
    def http = new HTTPBuilder()
    try {
        http.setHeaders([Authorization: 'Basic ' + 'user:pass'.bytes.encodeBase64().toString()])
        http.request(params.url, Method.GET, ContentType.BINARY) { req ->
            response.success = { resp, retour ->
                result = retour.bytes
            }
        }
    } catch (IOException | URISyntaxException e) { }
}

if(result) {
    // on renvoie au navigateur le contenu de l'image
    response.status = HttpServletResponse.SC_OK
    response.contentType = 'image/x-png'
    response.outputStream << result
    response.outputStream.flush()
}
else {
    response.status = HttpServletResponse.SC_NO_CONTENT
}
}