Get started with mapbox-gl-export CDN

MIT licensed

Mapbox-gl-export: Exports Mapbox GL JS maps as images or GeoJSON.

Tags:
  • mapbox
  • mapbox-gl-js
  • export
  • image
  • pdf

Stable version

Copied!

How to start using mapbox-gl-export CDN


<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://api.mapbox.com/styles/v1/mapbox/light-v10/maps/mapbox.html?access_token=YOUR_ACCESS_TOKEN">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/mapbox-gl.js"></script>
  <script src="https://cdn.cdnhub.io/mapbox-gl-export/2.0.2/mapbox-gl-export.js"></script>
  <style>
    #map {
      height: 100vh;
      width: 100%;
    }
  </style>
</head>
<body>
  <div id="map"></div>
  <script>
    mapboxgl.accessToken = 'YOUR_ACCESS_TOKEN';

    const map = new mapboxgl.Map({
      container: 'map',
      style: 'mapbox://styles/mapbox/light-v10',
      center: [-122.4194, 37.7749],
      zoom: 12
    });

    map.on('load', () => {
      map.addControl(new mapboxgl.NavigationControl());

      // Add a source and a layer for the data you want to export.
      map.addSource('data', {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: [
            {
              type: 'Feature',
              properties: {},
              geometry: {
                type: 'Point',
                coordinates: [-122.4194, 37.7749]
              }
            }
          ]
        }
      });

      map.addLayer({
        id: 'point-layer',
        type: 'circle',
        source: 'data',
        paint: {
          'circle-radius': 5,
          'circle-color': 'red'
        }
      });

      // Export the map as a GeoJSON file.
      const exportOptions = {
        type: 'GeoJSON',
        preserveTopology: false,
        includeAssets: true
      };

      mapboxgl.export(map, exportOptions)
        .then((data) => {
          const url = URL.createObjectURL(new Blob([JSON.stringify(data)], { type: 'application/json' }));
          const link = document.createElement('a');
          link.href = url;
          link.download = 'map_export.geojson';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          URL.revokeObjectURL(url);
        })
        .catch((error) => {
          console.error('Error exporting map:', error);
        });
    });
  </script>
</body>
</html>
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!

All versions