Edit

Map Export

Null Island
Download PNG

Example of exporting a map as a PNG image.

Example of exporting a map as a PNG image. This example use the html-to-image library.

index.html<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Map Export</title>
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
      .overlay {
        background-color: yellow;
        border-radius: 6px;
        padding: 4px;
        white-space: nowrap;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <div style="display: none;">
      <div class="overlay" id="null">Null Island</div>
    </div>
    <a id="export-png" class="btn btn-default"><i class="fa fa-download"></i> Download PNG</a>
    <a id="image-download" download="map.png"></a>
    <script src="index.js"></script>
  </body>
</html>
index.jsimport 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import Overlay from 'ol/Overlay';
import GeoJSON from 'ol/format/GeoJSON';
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
import {OSM, Vector as VectorSource} from 'ol/source';

import {toPng} from 'html-to-image';

var map = new Map({
  layers: [
    new TileLayer({
      source: new OSM()
    }),
    new VectorLayer({
      source: new VectorSource({
        url: 'data/geojson/countries.geojson',
        format: new GeoJSON()
      })
    })
  ],
  target: 'map',
  view: new View({
    center: [0, 0],
    zoom: 2
  })
});

map.addOverlay(new Overlay({
  position: [0, 0],
  element: document.getElementById('null')
}));


// export options for html-to-image.
// See: https://github.com/bubkoo/html-to-image#options
var exportOptions = {
  filter: function(element) {
    return element.className ? element.className.indexOf('ol-control') === -1 : true;
  }
};

document.getElementById('export-png').addEventListener('click', function() {
  map.once('rendercomplete', function() {
    toPng(map.getTargetElement(), exportOptions)
      .then(function(dataURL) {
        var link = document.getElementById('image-download');
        link.href = dataURL;
        link.click();
      });
  });
  map.renderSync();
});
package.json{
  "name": "export-map",
  "dependencies": {
    "ol": "6.0.1",
    "html-to-image": "^0.1.0"
  },
  "devDependencies": {
    "parcel": "1.11.0"
  },
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build --experimental-scope-hoisting --public-url . index.html"
  }
}