使用控制比例线保存地图

Save the map with the control scale-line

我可以将地图保存为 PNG 图像,但我如何才能将比例尺控件添加到此 canvas?

// export png
document.getElementById('export-png').addEventListener('click', function() {
  map.once('postcompose', function(event) {
    var canvasElement = event.context.canvas;
    var MIME_TYPE = "image/png";
    var imgURL = canvasElement.toDataURL(MIME_TYPE);
    var dlLink = document.createElement('a');
    dlLink.download = "carte"; //fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');
    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
  });
  map.renderSync();
});

刻度线控件是一个 HTML 元素,所以您不能按原样那样做。您需要在地图 canvas 本身上画一条线,每次地图移动后,更新该线以地图单位表示实际长度。

假设您使用的是公制投影,分辨率为 0.2 的 50 像素线表示

50px x 0.2m/px = 10m

在此处选中 link 以将地图导出为 PNG:

https://openlayers.org/en/v4.6.5/examples/export-map.html

我修改了代码,在 canvas 上画了一条 200 米长的线,并在上面写了 200 米来表示比例尺。它又快又脏,但应该为您指明方向。

// this example uses FileSaver.js for which we don't have an externs file.
var map = new ol.Map({
  layers: [
    new ol.layer.Tile({
      source: new ol.source.OSM()
    }),
    new ol.layer.Vector({
      source: new ol.source.Vector({
        url: 'https://openlayers.org/en/v4.6.5/examples/data/geojson/countries.geojson',
        format: new ol.format.GeoJSON()
      })
    })
  ],
  target: 'map',
  controls: ol.control.defaults({
    attributionOptions: {
      collapsible: false
    }
  }),
  view: new ol.View({
    center: ol.proj.transform([28.9, 41.1],"EPSG:4326","EPSG:3857"),
    zoom: 18
  })
});

document.getElementById('export-png').addEventListener('click', function() {
  map.once('postcompose', function(event) {
    var canvas = event.context.canvas;
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = "#0000FF";
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.moveTo(10, map.getSize()[1]-10);
    ctx.lineTo(200/map.getView().getResolution(), map.getSize()[1]-10);
    ctx.stroke();
    ctx.font = "20px Arial";
    ctx.fillText("200m", 10, map.getSize()[1]-10);
    if (navigator.msSaveBlob) {
      navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
    } else {
      canvas.toBlob(function(blob) {
        saveAs(blob, 'map.png');
      });
    }
  });
  map.renderSync();
});

请注意,在下一个版本中 https://github.com/openlayers/openlayers/blob/master/changelog/upgrade-notes.md OpenLayers will change from having a single canvas for all layers to a canvas for each layer which won't be compatible with saving complete maps. However for 5.3 and below the ol-ext library includes canvas controls for scaleline, attribution and title https://viglino.github.io/ol-ext/examples/canvas/map.canvas.control.html In many cases the code for individual controls can be copied from the source and customised without needing the whole library https://viglino.github.io/ol-ext/dist/ol-ext.js