block by ThomasG77 3047b6072f0411d11d23cfed1fdb2c5c

Make OpenLayers GL JS sample for IGN plan. Live demo at https://gist.githack.com/ThomasG77/3047b6072f0411d11d23cfed1fdb2c5c/raw/9ac46a1652d47352b3d55d5bf9ac4840d383fa3b/index.html

Full Screen

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Tuiles vecteur OpenLayers</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1" />

  <!-- Openlayers -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ol@v9.1.0/ol.css" />
  <script src="https://cdn.jsdelivr.net/npm/ol@v9.1.0/dist/ol.js"></script>
  <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL,Object.assign"></script>
  <script src="https://unpkg.com/ol-mapbox-style@12.2.0/dist/olms.js"></script>
  <style type="text/css">
       html, body {
        height: 100%;
        padding: 0;
        margin: 0;
      }
      #map {
        /* configure the size of the map */
        width: 100%;
        height: 100%;
      }
  </style>
  
</head>
<body >

  <!-- DIV pour la carte -->
  <div id="map"></div>
  <script>
    var map = new ol.Map({
      target: 'map',
      view: new ol.View ({
        zoom: 5,
        center: ol.proj.fromLonLat([3.389162, 46.852644])
      }),
      interactions: ol.interaction.defaults.defaults()
    });
    const url_style = "https://data.geopf.fr/annexes/ressources/vectorTiles/styles/PLAN.IGN/standard.json";
    fetch(url_style).then(res => res.json()).then(style => {
      // Patching or not below line is ignored on OpenLayers side. Always considered xyz
      // style.sources.plan_ign.scheme = 'xyz';
      const attribution = 'Données cartographiques : © IGN'
      style.sources.plan_ign.attribution = attribution;
      const url_pbf = style.sources.plan_ign.tiles[0];
      var vlayer = new ol.layer.VectorTile({
        title: "Plan IGN vecteur",
        renderMode: 'hybrid',
        declutter: true
      });

      olms.applyStyle(vlayer, style, 'plan_ign').then(function (e) {
        vlayer.setSource(
          new ol.source.VectorTile({
            tilePixelRatio: 1,
            tileGrid: ol.tilegrid.createXYZ({ maxZoom: 19 }),
            format: new ol.format.MVT(),
            url : url_pbf,
            attributions: attribution,
          })
        )
      });
      map.addLayer(vlayer);
    })
    
  </script>
</body>
</html>