2016-08-02 36 views
0

我想在爲Google Maps API創建TileOverlay時訪問需要用戶/傳遞的不同主機上託管的一些自定義地圖塊。如何在ImageMapType的getTileUrl中添加授權標頭Javascript

所以這是我當前的代碼的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); 

由於連接返回401 Anauthorized,我無法訪問的瓷磚。我怎麼能通過JavaScript/Jquery中的授權標題讓URL知道我有權訪問這些瓷磚?

我在尋找這樣一個解決方案,但在Javascript:Adding an Authorization header in getTileUrl for Maps Tile Android

+0

您是否在尋找這個? https://developers.google.com/maps/documentation/javascript/get-api-key?hl=zh-CN –

+0

我正在尋找這樣的解決方案:http://stackoverflow.com/questions/34739880/adding-an -authorization-header-in-gettileurl-for-maps-tile-android,但在Javascript中。 – Ulyanca

回答

1

我發現通過impementing代理的解決方案。 這裏是代碼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 
    }); 

我控制器代碼:

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 
} 
} 
1

當用戶代理想要發送它可以使用授權領域的服務器身份驗證憑據。

的授權字段的結構如下:

用戶名和密碼與單個結腸組合。 生成的字符串使用Base64的RFC2045-MIME變體進行編碼,但不限於76字符/行。 然後將授權方法和空格(即「基本」)放在編碼的字符串之前。

來源:Http Authentication

$.ajax({ 
     type: // POST OR GET, 
     url: //your url, 
     headers: { 
      Authorization:"Basic "+new Buffer(name+':'+pass).toString('base64'), 
      "Content-Type" : //according to you 
     } 
     }) 
     .done(function(data) { }); 
+0

儘管此代碼可能會回答問題,但提供有關* how *和/或* why *解決問題的其他上下文會提高答案的長期價值。 –

+0

他問如何在javascript/jquery中傳遞授權標頭,那是怎麼傳遞的。 –

+0

即使發佈的代碼確實回答了這個問題,一個好的答案將有助於解釋爲什麼代碼可以解決問題。在StackOverflow上,僅有代碼的答案被認爲是低質量的。 –