Mapbox GL JS:将地图导出为PNG或PDF? [英] Mapbox GL JS: Export map to PNG or PDF?

查看:1590
本文介绍了Mapbox GL JS:将地图导出为PNG或PDF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mapbox GL JS版本0.32.是否可以将地图导出为高分辨率PNG或PDF?

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.

我尝试使用 preserveDrawingBuffer选项:

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());

这会在控制台中输出一个长数据URL,但会将其复制并粘贴到一个base64转换器似乎产生了一个空图像.

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)
});

控制台输出如下: http://pastebin.com/raw/KhyJkJWJ

推荐答案

主要有两个问题:

1.如何获取地图画布作为图像?

实际上,您在做正确的事,但为时过早.触发load事件时,给该映射表一些时间来加载和获取图像数据:

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.如何获得高分辨率的图像?

通过根据目标dpi更改window.devicePixelRatio,您可以欺骗浏览器生成高分辨率输出.我在Matthew Petroff创建的实现中找到了该解决方案,请参见 https://github.com/mpetroff上的代码/print-maps . 这是他用于生成高分辨率输出的技巧:

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}
});

来源

这篇关于Mapbox GL JS:将地图导出为PNG或PDF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆