简体   繁体   中英

How to use standard OpenStreetMap tile servers with Mapbox GL JS?

I'm trying to use Mapbox GL in combination with the plain public OSM tile servers. Following the example of how to add a raster tile source , my take on a minimal example looks like this:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <title>Minimal OSM Test</title>
  <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
  <script src="https://api.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.js"></script>
  <link href="https://api.mapbox.com/mapbox-gl-js/v1.8.1/mapbox-gl.css" rel="stylesheet" />
  <style>
    body {
      margin: 0;
      padding: 0;
    }
    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      border: solid 1px #000000;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <script>
    var map = new mapboxgl.Map({
      container: 'map',
      style: {
        version: 8,
        sources: {
          osm: {
            type: 'raster',
            tiles: ["https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"],
          }
        },
        layers: [{
          id: 'osm',
          type: 'raster',
          source: 'osm',
        }],
      }
    });
  </script>

</body>

</html>

Unfortunately, this doesn't seem to work: The map does not show anything and the browser console is full of blocked cross-origin requests errors.

With other map libraries like Leaflet or OpenLayers, I have no problems connecting to the public OSM servers.

How can I make this work in Mapbox GL JS?

Synthesizing the insights in the comments above, as well as adding an important note about attribution, this JSFiddle achieves what you are looking for: https://jsfiddle.net/g1rwx8kp/ .

The following changes were made:

  • As noted by chris-g , you should remove the {s} from the tile url.
  • As noted by AndrewHarvey , specifying tileSize is good practice. Here I included tileSize: 256 .
  • You should pass a string to the attribution option in order to display relevant attribution of your tile and data sources on the map. I included an example in the JSFiddle above, though as I disclaimer, I cannot vouch for its accuracy and it likely should be further refined . Per the documentation on tile usage policy:

    OpenStreetMap data is free for everyone to use. Our tile servers are not.

    Further, "clearly display license attribution" is listed as a requirement for usage of the tile servers. As such, I'd recommend carefully reviewing these policies before frequently connecting to public OSM servers. Or, maybe someone else with experience using these tile serves can provide more insight!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM