刻度线控件是一个 HTML 元素,所以你真的不能这样做。您需要在地图画布本身上绘制一条线,并在每次地图移动后更新该线,以地图单位表示实际长度。
假设您使用的是公制投影,则分辨率为 0.2 的 50 像素线表示
50px x 0.2m/px = 10m
查看此处的链接以将地图导出为 PNG:
https://openlayers.org/en/v4.6.5/examples/export-map.html
我修改了代码,在画布上画了一条 200 米长的线,并在上面写了 200m 来表示比例。它又快又脏,但应该为您指明方向。
// 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();
});