Mapbox GL JS: Export map to PNG or PDF?

Richard picture Richard · Feb 27, 2017 · Viewed 8.9k times · Source

I'm using Mapbox GL JS version 0.32. Is there a way to export the map to a high-res PNG or PDF?

Obviously, I can just screenshot, but it would be nice if there was a more formal way.

I found this repo, but it looks old and isn't clear how it works.

I tried using the preserveDrawingBuffer option:

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    minZoom: 4,
    maxZoom: 14,
    center: [-2.0, 53.3],
    preserveDrawingBuffer: true
});
console.log(map.getCanvas().toDataURL());

This outputs a long data URL in the console, but copying and pasting it into a base64 converter just seems to produce an empty image.

UPDATE: This is my new code, in full:

mapboxgl.accessToken = 'pk.eyXXX';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v9',
    minZoom: 4,
    maxZoom: 14,
    center: [-2.0, 53.3],
    preserveDrawingBuffer: true
});
var dpi = 300;
Object.defineProperty(window, 'devicePixelRatio', {
    get: function() {return dpi / 96}
});

map.on('load', function () {
    var content = map.getCanvas().toDataURL();
    console.log(content)
});

The output to the console is this: http://pastebin.com/raw/KhyJkJWJ

Answer

sgelb picture sgelb · Feb 28, 2017

There are two main questions:

1. How do I get the map canvas as an image?

Actually, you are doing the right thing, but just too early. Give that map some time to load and fetch the image data when the load event is triggered:

map.on('load', () => console.log(map.getCanvas().toDataURL()));

2. How do I get that image in high-res?

By changing window.devicePixelRatio according to your destination dpi, you can trick your browser into generating high-res output. I found that solution in an implementation created by Matthew Petroff, see his code on https://github.com/mpetroff/print-maps. This is the trick he's using for generating high-res output:

Object.defineProperty(window, 'devicePixelRatio', {
    get: function() {return dpi / 96}
});

Source