我试图按照传单地图教程(使用Mapbox磁贴)进行操作,以便基本上在我的网页中显示地图。我已确保创建个人令牌,并按照建议将其替换在tileLayer中。但是我总是在控制台中收到“无法加载资源:服务器以401(未经授权)的状态响应”错误。

我的代码与教程中的代码基本相同,除了我添加了生成的令牌:

<html>
<head>
 <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
   integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ=="
   crossorigin=""/>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"
   integrity="sha512-/Nsx9X4HebavoBvEBuyp3I7od5tA0UzAxs+j83KgC8PU0kgB4XiK4Lfe4y4cgBtaRJQEIFCW+oC506aPT2L1zw=="
   crossorigin=""></script>


</head>
<body>

 <div id="mapid"></div>
</body>
</html>
<script type="text/javascript">
document.onload = loadMap();

function loadMap() {

  var map = L.map('mapid').setView([51.505, -0.09], 13);


  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={sk.eyJ1IjoiaXFhcmNobGkiLCJhIjoiY2pqZTN1OTNxMGNubDNwbXNhbDNka2J4ZiJ9.UKoT12YRTSSUEnIGHyiScQ}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox-outdoors',
    accessToken: 'sk.eyJ1IjoiaXFhcmNobGkiLCJhIjoiY2pqZTN1OTNxMGNubDNwbXNhbDNka2J4ZiJ9.UKoT12YRTSSUEnIGHyiScQ'
  }).addTo(map);

}

</script>

最佳答案

您不应该将令牌放在URL中。 acces_token={accessToken}将在加载javascript时替换。您只需要像在这里一样指定密钥即可:

accessToken:'*cut key away*'

因此,这应该工作:

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox-outdoors',
    accessToken: 'sk.eyJ1IjoiaXFhcmNobGkiLCJhIjoiY2pqZTN1OTNxMGNubDNwbXNhbDNka2J4ZiJ9.UKoT12YRTSSUEnIGHyiScQ'
  }).addTo(map);

09-10 18:29