Fix: png correctly outputs all markers now

This commit is contained in:
Pieter Vander Vennet 2023-06-04 00:43:32 +02:00
parent 47ae4cb456
commit 905f796baa
20 changed files with 1509 additions and 842 deletions

View file

@ -1,54 +0,0 @@
import Combine from "../Base/Combine"
import Translations from "../i18n/Translations"
import {UIEventSource} from "../../Logic/UIEventSource"
import Toggle from "../Input/Toggle"
import {SubtleButton} from "../Base/SubtleButton"
import Svg from "../../Svg"
import ExportPDF from "../ExportPDF"
import FilteredLayer from "../../Models/FilteredLayer"
import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig"
import {BBox} from "../../Logic/BBox"
import Loc from "../../Models/Loc"
export default class AllDownloads extends SubtleButton {
constructor(
isShown: UIEventSource<boolean>,
state: {
filteredLayers: UIEventSource<FilteredLayer[]>
layoutToUse: LayoutConfig
currentBounds: UIEventSource<BBox>
locationControl: UIEventSource<Loc>
featureSwitchExportAsPdf: UIEventSource<boolean>
featureSwitchEnableExport: UIEventSource<boolean>
}
) {
const isExporting = new UIEventSource(false, "Pdf-is-exporting")
const generatePdf = () => {
isExporting.setData(true)
new ExportPDF({
freeDivId: "belowmap",
location: state.locationControl,
layout: state.layoutToUse,
}).isRunning.addCallbackAndRun((isRunning) => isExporting.setData(isRunning))
}
const loading = Svg.loading_svg().SetClass("animate-rotate")
const dloadTrans = Translations.t.general.download
const icon = new Toggle(loading, Svg.floppy_svg(), isExporting)
const text = new Toggle(
dloadTrans.exporting.Clone(),
new Combine([
dloadTrans.downloadAsPdf.Clone().SetClass("font-bold"),
dloadTrans.downloadAsPdfHelper.Clone(),
])
.SetClass("flex flex-col")
.onClick(() => {
generatePdf()
}),
isExporting
)
super(icon, text)
}
}

View file

@ -1,300 +0,0 @@
import { SubtleButton } from "../Base/SubtleButton"
import Svg from "../../Svg"
import Translations from "../i18n/Translations"
import { Utils } from "../../Utils"
import Combine from "../Base/Combine"
import CheckBoxes from "../Input/Checkboxes"
import { GeoOperations } from "../../Logic/GeoOperations"
import Toggle from "../Input/Toggle"
import Title from "../Base/Title"
import { Store } from "../../Logic/UIEventSource"
import SimpleMetaTagger from "../../Logic/SimpleMetaTagger"
import LayoutConfig from "../../Models/ThemeConfig/LayoutConfig"
import { BBox } from "../../Logic/BBox"
import geojson2svg from "geojson2svg"
import LayerConfig from "../../Models/ThemeConfig/LayerConfig"
import { SpecialVisualizationState } from "../SpecialVisualization"
import { Feature, FeatureCollection } from "geojson"
import { GeoIndexedStoreForLayer } from "../../Logic/FeatureSource/Actors/GeoIndexedStore"
import LayerState from "../../Logic/State/LayerState"
import { PriviligedLayerType } from "../../Models/Constants"
export class DownloadPanel extends Toggle {
constructor(state: SpecialVisualizationState) {
const t = Translations.t.general.download
const name = state.layout.id
const includeMetaToggle = new CheckBoxes([t.includeMetaData])
const metaisIncluded = includeMetaToggle.GetValue().map((selected) => selected.length > 0)
const buttonGeoJson = new SubtleButton(
Svg.floppy_svg(),
new Combine([
t.downloadGeojson.SetClass("font-bold"),
t.downloadGeoJsonHelper,
]).SetClass("flex flex-col")
).OnClickWithLoading(t.exporting, async () => {
const geojson = DownloadPanel.getCleanGeoJson(state, metaisIncluded.data)
Utils.offerContentsAsDownloadableFile(
JSON.stringify(geojson, null, " "),
`MapComplete_${name}_export_${new Date().toISOString().substr(0, 19)}.geojson`,
{
mimetype: "application/vnd.geo+json",
}
)
})
const buttonCSV = new SubtleButton(
Svg.floppy_svg(),
new Combine([t.downloadCSV.SetClass("font-bold"), t.downloadCSVHelper]).SetClass(
"flex flex-col"
)
).OnClickWithLoading(t.exporting, async () => {
const geojson = DownloadPanel.getCleanGeoJson(state, metaisIncluded.data)
const csv = GeoOperations.toCSV(geojson.features)
Utils.offerContentsAsDownloadableFile(
csv,
`MapComplete_${name}_export_${new Date().toISOString().substr(0, 19)}.csv`,
{
mimetype: "text/csv",
}
)
})
const buttonSvg = new SubtleButton(
Svg.floppy_svg(),
new Combine([t.downloadAsSvg.SetClass("font-bold"), t.downloadAsSvgHelper]).SetClass(
"flex flex-col"
)
).OnClickWithLoading(t.exporting, async () => {
const geojson = DownloadPanel.getCleanGeoJsonPerLayer(state, metaisIncluded.data)
const maindiv = document.getElementById("maindiv")
const layers = state.layout.layers.filter((l) => l.source !== null)
const csv = DownloadPanel.asSvg(geojson, {
layers,
mapExtent: state.mapProperties.bounds.data,
width: maindiv.offsetWidth,
height: maindiv.offsetHeight,
})
Utils.offerContentsAsDownloadableFile(
csv,
`MapComplete_${name}_export_${new Date().toISOString().substr(0, 19)}.svg`,
{
mimetype: "image/svg+xml",
}
)
})
const buttonPng = new SubtleButton(
Svg.floppy_svg(),
new Combine([t.downloadAsPng.SetClass("font-bold"), t.downloadAsPngHelper])
).OnClickWithLoading(t.exporting, async () => {
const gpsLayer = state.layerState.filteredLayers.get(
<PriviligedLayerType>"gps_location"
)
const gpsIsDisplayed = gpsLayer.isDisplayed.data
try {
gpsLayer.isDisplayed.setData(false)
const png = await state.mapProperties.exportAsPng()
Utils.offerContentsAsDownloadableFile(
png,
`MapComplete_${name}_export_${new Date().toISOString().substr(0, 19)}.png`,
{
mimetype: "image/png",
}
)
} catch (e) {
console.error(e)
} finally {
gpsLayer.isDisplayed.setData(gpsIsDisplayed)
}
})
const downloadButtons = new Combine([
new Title(t.title),
buttonGeoJson,
buttonCSV,
buttonSvg,
buttonPng,
includeMetaToggle,
t.licenseInfo.SetClass("link-underline"),
]).SetClass("w-full flex flex-col")
super(
downloadButtons,
t.noDataLoaded,
state.dataIsLoading.map((x) => !x)
)
}
/**
* Converts a geojson to an SVG
*
* const feature = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "LineString",
* "coordinates": [
* [-180, 80],
* [180, -80]
* ]
* }
* }
* const perLayer = new Map<string, any[]>([["testlayer", [feature]]])
* DownloadPanel.asSvg(perLayer).replace(/\n/g, "") // => `<svg width="1000px" height="1000px" viewBox="0 0 1000 1000"> <g id="testlayer" inkscape:groupmode="layer" inkscape:label="testlayer"> <path d="M0,27.77777777777778 1000,472.22222222222223" style="fill:none;stroke-width:1" stroke="#ff0000"/> </g></svg>`
*/
public static asSvg(
perLayer: Map<string, Feature[]>,
options?: {
layers?: LayerConfig[]
width?: 1000 | number
height?: 1000 | number
mapExtent?: BBox
unit?: "px" | "mm" | string
}
) {
options = options ?? {}
const width = options.width ?? 1000
const height = options.height ?? 1000
if (width <= 0 || height <= 0) {
throw "Invalid width of height, they should be > 0"
}
const unit = options.unit ?? "px"
const mapExtent = { left: -180, bottom: -90, right: 180, top: 90 }
if (options.mapExtent !== undefined) {
const bbox = options.mapExtent
mapExtent.left = bbox.minLon
mapExtent.right = bbox.maxLon
mapExtent.bottom = bbox.minLat
mapExtent.top = bbox.maxLat
}
console.log("Generateing svg, extent:", { mapExtent, width, height })
const elements: string[] = []
for (const layer of Array.from(perLayer.keys())) {
const features = perLayer.get(layer)
if (features.length === 0) {
continue
}
const layerDef = options?.layers?.find((l) => l.id === layer)
const rendering = layerDef?.lineRendering[0]
const converter = geojson2svg({
viewportSize: { width, height },
mapExtent,
output: "svg",
attributes: [
{
property: "style",
type: "static",
value: "fill:none;stroke-width:1",
},
{
property: "properties.stroke",
type: "dynamic",
key: "stroke",
},
],
})
for (const feature of features) {
const stroke =
rendering?.color?.GetRenderValue(feature.properties)?.txt ?? "#ff0000"
const color = Utils.colorAsHex(Utils.color(stroke))
feature.properties.stroke = color
}
const groupPaths: string[] = converter.convert({ type: "FeatureCollection", features })
const group =
` <g id="${layer}" inkscape:groupmode="layer" inkscape:label="${layer}">\n` +
groupPaths.map((p) => " " + p).join("\n") +
"\n </g>"
elements.push(group)
}
const w = width
const h = height
const header = `<svg width="${w}${unit}" height="${h}${unit}" viewBox="0 0 ${w} ${h}">`
return header + "\n" + elements.join("\n") + "\n</svg>"
}
private static getCleanGeoJson(
state: {
layout: LayoutConfig
mapProperties: { bounds: Store<BBox> }
perLayer: ReadonlyMap<string, GeoIndexedStoreForLayer>
layerState: LayerState
},
includeMetaData: boolean
): FeatureCollection {
const featuresPerLayer = DownloadPanel.getCleanGeoJsonPerLayer(state, includeMetaData)
const features = [].concat(...Array.from(featuresPerLayer.values()))
return {
type: "FeatureCollection",
features,
}
}
/**
* Returns a new feature of which all the metatags are deleted
*/
private static cleanFeature(f: Feature): Feature {
f = {
type: f.type,
geometry: { ...f.geometry },
properties: { ...f.properties },
}
for (const key in f.properties) {
if (key === "_lon" || key === "_lat") {
continue
}
if (key.startsWith("_")) {
delete f.properties[key]
}
}
const datedKeys = [].concat(
SimpleMetaTagger.metatags
.filter((tagging) => tagging.includesDates)
.map((tagging) => tagging.keys)
)
for (const key of datedKeys) {
delete f.properties[key]
}
return f
}
private static getCleanGeoJsonPerLayer(
state: {
layout: LayoutConfig
mapProperties: { bounds: Store<BBox> }
perLayer: ReadonlyMap<string, GeoIndexedStoreForLayer>
layerState: LayerState
},
includeMetaData: boolean
): Map<string, Feature[]> {
const featuresPerLayer = new Map<string, any[]>()
const neededLayers = state.layout.layers.filter((l) => l.source !== null).map((l) => l.id)
const bbox = state.mapProperties.bounds.data
for (const neededLayer of neededLayers) {
const indexedFeatureSource = state.perLayer.get(neededLayer)
let features = indexedFeatureSource.GetFeaturesWithin(bbox)
// The 'indexedFeatureSources' contains _all_ features, they are not filtered yet
const filter = state.layerState.filteredLayers.get(neededLayer)
features = features.filter((f) =>
filter.isShown(f.properties, state.layerState.globalFilters.data)
)
if (!includeMetaData) {
features = features.map((f) => DownloadPanel.cleanFeature(f))
}
featuresPerLayer.set(neededLayer, features)
}
return featuresPerLayer
}
}

View file

@ -0,0 +1,85 @@
<script lang="ts">
import type {SpecialVisualizationState} from "../SpecialVisualization";
import {ArrowDownTrayIcon} from "@babeard/svelte-heroicons/mini";
import Tr from "../Base/Tr.svelte";
import Translations from "../i18n/Translations";
import type {FeatureCollection} from "geojson";
import Loading from "../Base/Loading.svelte";
import {Translation} from "../i18n/Translation";
import DownloadHelper from "./DownloadHelper";
import {Utils} from "../../Utils";
import type {PriviligedLayerType} from "../../Models/Constants";
export let state: SpecialVisualizationState
export let extension: string
export let mimetype: string
export let construct: (geojsonCleaned: FeatureCollection) => (Blob | string) | Promise<void>
export let mainText: Translation
export let helperText: Translation
export let metaIsIncluded: boolean
let downloadHelper: DownloadHelper = new DownloadHelper(state)
const t = Translations.t.general.download
let isExporting = false
let isError = false
async function clicked() {
isExporting = true
const gpsLayer = state.layerState.filteredLayers.get(
<PriviligedLayerType>"gps_location"
)
state.lastClickObject.features.setData([])
const gpsIsDisplayed = gpsLayer.isDisplayed.data
try {
gpsLayer.isDisplayed.setData(false)
const geojson: FeatureCollection = downloadHelper.getCleanGeoJson(metaIsIncluded)
const name = state.layout.id
const promise = construct(geojson)
let data: Blob | string
if (typeof promise === "string") {
data = promise
} else if (typeof promise["then"] === "function") {
data = await <Promise<Blob | string>> promise
} else {
data = <Blob>promise
}
console.log("Got data", data)
Utils.offerContentsAsDownloadableFile(
data,
`MapComplete_${name}_export_${new Date().toISOString().substr(0, 19)}.${extension}`,
{
mimetype,
}
)
} catch (e) {
isError = true
}
gpsLayer.isDisplayed.setData(gpsIsDisplayed)
isExporting = false
}
</script>
{#if isError}
<Tr cls="alert" t={Translations.t.error}/>
{:else if isExporting}
<Loading>
<Tr t={t.exporting}/>
</Loading>
{:else}
<button class="flex w-full" on:click={clicked}>
<slot name="image">
<ArrowDownTrayIcon class="w-12 h-12 mr-2"/>
</slot>
<span class="flex flex-col items-start">
<Tr t={mainText}/>
<Tr t={helperText} cls="subtle"/>
</span>
</button>
{/if}

View file

@ -0,0 +1,181 @@
import {SpecialVisualizationState} from "../SpecialVisualization";
import {Feature, FeatureCollection} from "geojson";
import {BBox} from "../../Logic/BBox";
import LayerConfig from "../../Models/ThemeConfig/LayerConfig";
import {Utils} from "../../Utils";
import SimpleMetaTagger from "../../Logic/SimpleMetaTagger"
import geojson2svg from "geojson2svg"
/**
* Exposes the download-functionality
*/
export default class DownloadHelper {
private readonly _state: SpecialVisualizationState;
constructor(state: SpecialVisualizationState) {
this._state = state;
}
/**
* Returns a new feature of which all the metatags are deleted
*/
private static cleanFeature(f: Feature): Feature {
f = {
type: f.type,
geometry: { ...f.geometry },
properties: { ...f.properties },
}
for (const key in f.properties) {
if (key === "_lon" || key === "_lat") {
continue
}
if (key.startsWith("_")) {
delete f.properties[key]
}
}
const datedKeys = [].concat(
SimpleMetaTagger.metatags
.filter((tagging) => tagging.includesDates)
.map((tagging) => tagging.keys)
)
for (const key of datedKeys) {
delete f.properties[key]
}
return f
}
public getCleanGeoJson(
includeMetaData: boolean
): FeatureCollection {
const state = this._state
const featuresPerLayer = this.getCleanGeoJsonPerLayer(includeMetaData)
const features = [].concat(...Array.from(featuresPerLayer.values()))
return {
type: "FeatureCollection",
features,
}
}
/**
* Converts a geojson to an SVG
*
* const feature = {
* "type": "Feature",
* "properties": {},
* "geometry": {
* "type": "LineString",
* "coordinates": [
* [-180, 80],
* [180, -80]
* ]
* }
* }
* const perLayer = new Map<string, any[]>([["testlayer", [feature]]])
* DownloadHelper.asSvg(perLayer).replace(/\n/g, "") // => `<svg width="1000px" height="1000px" viewBox="0 0 1000 1000"> <g id="testlayer" inkscape:groupmode="layer" inkscape:label="testlayer"> <path d="M0,27.77777777777778 1000,472.22222222222223" style="fill:none;stroke-width:1" stroke="#ff0000"/> </g></svg>`
*/
public asSvg(
options?: {
layers?: LayerConfig[]
width?: 1000 | number
height?: 1000 | number
mapExtent?: BBox
unit?: "px" | "mm" | string
}
) {
const perLayer = this._state.perLayer
options = options ?? {}
const width = options.width ?? 1000
const height = options.height ?? 1000
if (width <= 0 || height <= 0) {
throw "Invalid width of height, they should be > 0"
}
const unit = options.unit ?? "px"
const mapExtent = { left: -180, bottom: -90, right: 180, top: 90 }
if (options.mapExtent !== undefined) {
const bbox = options.mapExtent
mapExtent.left = bbox.minLon
mapExtent.right = bbox.maxLon
mapExtent.bottom = bbox.minLat
mapExtent.top = bbox.maxLat
}
console.log("Generateing svg, extent:", { mapExtent, width, height })
const elements: string[] = []
for (const layer of Array.from(perLayer.keys())) {
const features = perLayer.get(layer).features.data
if (features.length === 0) {
continue
}
const layerDef = options?.layers?.find((l) => l.id === layer)
const rendering = layerDef?.lineRendering[0]
const converter = geojson2svg({
viewportSize: { width, height },
mapExtent,
output: "svg",
attributes: [
{
property: "style",
type: "static",
value: "fill:none;stroke-width:1",
},
{
property: "properties.stroke",
type: "dynamic",
key: "stroke",
},
],
})
for (const feature of features) {
const stroke =
rendering?.color?.GetRenderValue(feature.properties)?.txt ?? "#ff0000"
const color = Utils.colorAsHex(Utils.color(stroke))
feature.properties.stroke = color
}
const groupPaths: string[] = converter.convert({ type: "FeatureCollection", features })
const group =
` <g id="${layer}" inkscape:groupmode="layer" inkscape:label="${layer}">\n` +
groupPaths.map((p) => " " + p).join("\n") +
"\n </g>"
elements.push(group)
}
const w = width
const h = height
const header = `<svg width="${w}${unit}" height="${h}${unit}" viewBox="0 0 ${w} ${h}">`
return header + "\n" + elements.join("\n") + "\n</svg>"
}
public getCleanGeoJsonPerLayer(
includeMetaData: boolean
): Map<string, Feature[]> {
const state = this._state
const featuresPerLayer = new Map<string, any[]>()
const neededLayers = state.layout.layers.filter((l) => l.source !== null).map((l) => l.id)
const bbox = state.mapProperties.bounds.data
for (const neededLayer of neededLayers) {
const indexedFeatureSource = state.perLayer.get(neededLayer)
let features = indexedFeatureSource.GetFeaturesWithin(bbox)
// The 'indexedFeatureSources' contains _all_ features, they are not filtered yet
const filter = state.layerState.filteredLayers.get(neededLayer)
features = features.filter((f) =>
filter.isShown(f.properties, state.layerState.globalFilters.data)
)
if (!includeMetaData) {
features = features.map((f) => DownloadHelper.cleanFeature(f))
}
featuresPerLayer.set(neededLayer, features)
}
return featuresPerLayer
}
}

View file

@ -0,0 +1,94 @@
<script lang="ts">
import type {SpecialVisualizationState} from "../SpecialVisualization";
import Loading from "../Base/Loading.svelte";
import Translations from "../i18n/Translations";
import Tr from "../Base/Tr.svelte";
import DownloadHelper from "./DownloadHelper";
import DownloadButton from "./DownloadButton.svelte";
import {GeoOperations} from "../../Logic/GeoOperations";
export let state: SpecialVisualizationState
let isLoading = state.dataIsLoading
const t = Translations.t.general.download
const downloadHelper = new DownloadHelper(state)
let metaIsIncluded = false
const name = state.layout.id
function offerSvg(): string {
const maindiv = document.getElementById("maindiv")
const layers = state.layout.layers.filter((l) => l.source !== null)
return downloadHelper.asSvg({
layers,
mapExtent: state.mapProperties.bounds.data,
width: maindiv.offsetWidth,
height: maindiv.offsetHeight,
})
}
</script>
{#if $isLoading}
<Loading/>
{:else}
<div class="w-full flex flex-col"></div>
<h3>
<Tr t={t.title}/>
</h3>
<DownloadButton {state}
extension="geojson"
mimetype="application/vnd.geo+json"
construct={(geojson) => JSON.stringify(geojson)}
mainText={t.downloadGeojson}
helperText={t.downloadGeoJsonHelper}
{metaIsIncluded}/>
<DownloadButton {state}
extension="csv"
mimetype="text/csv"
construct={(geojson) => GeoOperations.toCSV(geojson)}
mainText={t.downloadCSV}
helperText={t.downloadCSVHelper}
{metaIsIncluded}/>
<label class="mb-8 mt-2">
<input type="checkbox" bind:value={metaIsIncluded}>
<Tr t={t.includeMetaData}/>
</label>
<DownloadButton {state} {metaIsIncluded}
extension="svg"
mimetype="image/svg+xml"
mainText={t.downloadAsSvg}
helperText={t.downloadAsSvgHelper}
construct={offerSvg}
/>
<DownloadButton {state} {metaIsIncluded}
extension="png"
mimetype="image/png"
mainText={t.downloadAsPng}
helperText={t.downloadAsPngHelper}
construct={_ => state.mapProperties.exportAsPng(4)}
/>
<DownloadButton {state}
mimetype="application/pdf"
extension="pdf"
mainText={t.downloadAsPdf}
helperText={t.downloadAsPdfHelper}
construct={_ => state.mapProperties.exportAsPng(4)}
/>
<Tr cls="link-underline" t={t.licenseInfo}/>
{/if}

View file

@ -1,196 +0,0 @@
import jsPDF from "jspdf"
import { UIEventSource } from "../Logic/UIEventSource"
import Minimap, { MinimapObj } from "./Base/Minimap"
import Loc from "../Models/Loc"
import BaseLayer from "../Models/BaseLayer"
import { FixedUiElement } from "./Base/FixedUiElement"
import Translations from "./i18n/Translations"
import State from "../State"
import Constants from "../Models/Constants"
import LayoutConfig from "../Models/ThemeConfig/LayoutConfig"
import FeaturePipeline from "../Logic/FeatureSource/FeaturePipeline"
import ShowDataLayer from "./ShowDataLayer/ShowDataLayer"
import { BBox } from "../Logic/BBox"
/**
* Creates screenshoter to take png screenshot
* Creates jspdf and downloads it
* - landscape pdf
*
* To add new layout:
* - add new possible layout name in constructor
* - add new layout in "PDFLayout"
* -> in there are more instructions
*/
export default class ExportPDF {
// dimensions of the map in milimeter
public isRunning = new UIEventSource(true)
// A4: 297 * 210mm
private readonly mapW = 297
private readonly mapH = 210
private readonly scaling = 2
private readonly freeDivId: string
private readonly _layout: LayoutConfig
private _screenhotTaken = false
constructor(options: {
freeDivId: string
location: UIEventSource<Loc>
background?: UIEventSource<BaseLayer>
features: FeaturePipeline
layout: LayoutConfig
}) {
this.freeDivId = options.freeDivId
this._layout = options.layout
const self = this
// We create a minimap at the given location and attach it to the given 'hidden' element
const l = options.location.data
const loc = {
lat: l.lat,
lon: l.lon,
zoom: l.zoom + 1,
}
const minimap = Minimap.createMiniMap({
location: new UIEventSource<Loc>(loc), // We remove the link between the old and the new UI-event source as moving the map while the export is running fucks up the screenshot
background: options.background,
allowMoving: false,
onFullyLoaded: (_) =>
window.setTimeout(() => {
if (self._screenhotTaken) {
return
}
try {
self.CreatePdf(minimap)
.then(() => self.cleanup())
.catch(() => self.cleanup())
} catch (e) {
console.error(e)
self.cleanup()
}
}, 500),
})
minimap.SetStyle(
`width: ${this.mapW * this.scaling}mm; height: ${this.mapH * this.scaling}mm;`
)
minimap.AttachTo(options.freeDivId)
// Next: we prepare the features. Only fully contained features are shown
minimap.leafletMap.addCallbackAndRunD((leaflet) => {
const bounds = BBox.fromLeafletBounds(leaflet.getBounds().pad(0.2))
options.features.GetTilesPerLayerWithin(bounds, (tile) => {
if (tile.layer.layerDef.minzoom > l.zoom) {
return
}
if (tile.layer.layerDef.id.startsWith("note_import")) {
// Don't export notes to import
return
}
new ShowDataLayer({
features: tile,
leafletMap: minimap.leafletMap,
layerToShow: tile.layer.layerDef,
doShowLayer: tile.layer.isDisplayed,
state: undefined,
})
})
})
State.state.AddAllOverlaysToMap(minimap.leafletMap)
}
private cleanup() {
new FixedUiElement("Screenshot taken!").AttachTo(this.freeDivId)
this._screenhotTaken = true
}
private async CreatePdf(minimap: MinimapObj) {
console.log("PDF creation started")
const t = Translations.t.general.pdf
const layout = this._layout
let doc = new jsPDF("landscape")
const image = await minimap.TakeScreenshot()
// @ts-ignore
doc.addImage(image, "PNG", 0, 0, this.mapW, this.mapH)
doc.setDrawColor(255, 255, 255)
doc.setFillColor(255, 255, 255)
doc.roundedRect(12, 10, 145, 25, 5, 5, "FD")
doc.setFontSize(20)
doc.textWithLink(layout.title.txt, 40, 18.5, {
maxWidth: 125,
url: window.location.href,
})
doc.setFontSize(10)
doc.text(t.generatedWith.txt, 40, 23, {
maxWidth: 125,
})
const backgroundLayer: BaseLayer = State.state.backgroundLayer.data
const attribution = new FixedUiElement(
backgroundLayer.layer().getAttribution() ?? backgroundLayer.name
).ConstructElement().textContent
doc.textWithLink(t.attr.txt, 40, 26.5, {
maxWidth: 125,
url: "https://www.openstreetmap.org/copyright",
})
doc.text(
t.attrBackground.Subs({
background: attribution,
}).txt,
40,
30
)
let date = new Date().toISOString().substr(0, 16)
doc.setFontSize(7)
doc.text(
t.versionInfo.Subs({
version: Constants.vNumber,
date: date,
}).txt,
40,
34,
{
maxWidth: 125,
}
)
// Add the logo of the layout
let img = document.createElement("img")
const imgSource = layout.icon
const imgType = imgSource.substring(imgSource.lastIndexOf(".") + 1)
img.src = imgSource
if (imgType.toLowerCase() === "svg") {
new FixedUiElement("").AttachTo(this.freeDivId)
// This is an svg image, we use the canvas to convert it to a png
const canvas = document.createElement("canvas")
const ctx = canvas.getContext("2d")
canvas.width = 500
canvas.height = 500
img.style.width = "100%"
img.style.height = "100%"
ctx.drawImage(img, 0, 0, 500, 500)
const base64img = canvas.toDataURL("image/png")
doc.addImage(base64img, "png", 15, 12, 20, 20)
} else {
try {
doc.addImage(img, imgType, 15, 12, 20, 20)
} catch (e) {
console.error(e)
}
}
doc.save(`MapComplete_${layout.title.txt}_${date}.pdf`)
this.isRunning.setData(false)
}
}

View file

@ -7,8 +7,8 @@ import {BBox} from "../../Logic/BBox"
import {ExportableMap, MapProperties} from "../../Models/MapProperties"
import SvelteUIElement from "../Base/SvelteUIElement"
import MaplibreMap from "./MaplibreMap.svelte"
import html2canvas from "html2canvas"
import {RasterLayerProperties} from "../../Models/RasterLayerProperties"
import * as htmltoimage from 'html-to-image';
/**
* The 'MapLibreAdaptor' bridges 'MapLibre' with the various properties of the `MapProperties`
@ -50,7 +50,7 @@ export class MapLibreAdaptor implements MapProperties, ExportableMap {
this._maplibreMap = maplibreMap
this.location = state?.location ?? new UIEventSource({lon: 0, lat: 0})
if(this.location.data){
if (this.location.data) {
// The MapLibre adaptor updates the element in the location and then pings them
// Often, code setting this up doesn't expect the object they pass in to be changed, so we create a copy
this.location.setData({...this.location.data})
@ -199,85 +199,95 @@ export class MapLibreAdaptor implements MapProperties, ExportableMap {
return url
}
async exportAsPng(): Promise<Blob> {
private static setDpi(drawOn: HTMLCanvasElement, ctx: CanvasRenderingContext2D, dpiFactor: number) {
drawOn.style.width = drawOn.style.width || drawOn.width + "px"
drawOn.style.height = drawOn.style.height || drawOn.height + "px"
// Resize canvas and scale future draws.
drawOn.width = Math.ceil(drawOn.width * dpiFactor)
drawOn.height = Math.ceil(drawOn.height * dpiFactor)
ctx.scale(dpiFactor, dpiFactor)
console.log("Resizing canvas with setDPI:", drawOn.width, drawOn.height, drawOn.style.width, drawOn.style.height)
}
public async exportAsPng(dpiFactor: number): Promise<Blob> {
const map = this._maplibreMap.data
if (!map) {
return undefined
}
const drawOn = document.createElement("canvas")
drawOn.width = map.getCanvas().width
drawOn.height = map.getCanvas().height
function setDPI(canvas, dpi) {
// Set up CSS size.
canvas.style.width = canvas.style.width || canvas.width + "px"
canvas.style.height = canvas.style.height || canvas.height + "px"
console.log("Canvas size:", drawOn.width, drawOn.height)
const ctx = drawOn.getContext("2d")
// Set up CSS size.
MapLibreAdaptor.setDpi(drawOn, ctx, dpiFactor)
// Resize canvas and scale future draws.
const scaleFactor = dpi / 96
canvas.width = Math.ceil(canvas.width * scaleFactor)
canvas.height = Math.ceil(canvas.height * scaleFactor)
const ctx = canvas.getContext("2d")
ctx?.scale(scaleFactor, scaleFactor)
}
await this.exportBackgroundOnCanvas(drawOn, ctx, dpiFactor)
drawOn.toBlob(blob => {
Utils.offerContentsAsDownloadableFile(blob, "bg.png")
})
console.log("Getting markers")
// MapLibreAdaptor.setDpi(drawOn, ctx, 1)
const markers = await this.drawMarkers(dpiFactor)
console.log("Drawing markers (" + markers.width + "*" + markers.height + ") onto drawOn (" + drawOn.width + "*" + drawOn.height + ")")
ctx.scale(1/dpiFactor,1/dpiFactor )
ctx.drawImage(markers, 0, 0, drawOn.width, drawOn.height)
ctx.scale(dpiFactor, dpiFactor)
markers.toBlob(blob => {
Utils.offerContentsAsDownloadableFile(blob, "markers.json")
})
this._maplibreMap.data?.resize()
return await new Promise<Blob>(resolve => drawOn.toBlob(blob => resolve(blob)))
}
/**
* Exports the background map and lines to PNG.
* Markers are _not_ rendered
*/
private async exportBackgroundOnCanvas(drawOn: HTMLCanvasElement, ctx: CanvasRenderingContext2D, dpiFactor: number = 1): Promise<void> {
const map = this._maplibreMap.data
// We draw the maplibre-map onto the canvas. This does not export markers
// Inspiration by https://github.com/mapbox/mapbox-gl-js/issues/2766
// Total hack - see https://stackoverflow.com/questions/42483449/mapbox-gl-js-export-map-to-png-or-pdf
const drawOn = document.createElement("canvas")
drawOn.width = document.documentElement.clientWidth
drawOn.height = document.documentElement.clientHeight
setDPI(drawOn, 4 * 96)
const destinationCtx = drawOn.getContext("2d")
{
// First, we draw the maplibre-map onto the canvas. This does not export markers
// Inspiration by https://github.com/mapbox/mapbox-gl-js/issues/2766
const promise = new Promise<void>((resolve) => {
map.once("render", () => {
destinationCtx.drawImage(map.getCanvas(), 0, 0)
resolve()
})
const promise = new Promise<void>((resolve) => {
map.once("render", () => {
ctx.drawImage(map.getCanvas(), 0, 0)
resolve()
})
})
while (!map.isStyleLoaded()) {
console.log("Waiting to fully load the style...")
await Utils.waitFor(100)
}
map.triggerRepaint()
await promise
// Reset the canvas width and height
map.resize()
while (!map.isStyleLoaded()) {
console.log("Waiting to fully load the style...")
await Utils.waitFor(100)
}
{
// now, we draw the markers on top of the map
map.triggerRepaint()
await promise
map.resize()
}
/* We use html2canvas for this, but disable the map canvas object itself:
* it cannot deal with this canvas object.
*
* We also have to patch up a few more objects
* */
const container = map.getCanvasContainer()
const origHeight = container.style.height
const origStyle = map.getCanvas().style.display
try {
map.getCanvas().style.display = "none"
if (!container.style.height) {
container.style.height = document.documentElement.clientHeight + "px"
}
await html2canvas(map.getCanvasContainer(), {
backgroundColor: "#00000000",
canvas: drawOn,
})
} catch (e) {
console.error(e)
} finally {
map.getCanvas().style.display = origStyle
container.style.height = origHeight
}
private async drawMarkers(dpiFactor: number): Promise<HTMLCanvasElement> {
const map = this._maplibreMap.data
if (!map) {
return undefined
}
// At last, we return the actual blob
return new Promise<Blob>((resolve) => drawOn.toBlob((data) => resolve(data)))
const width = map.getCanvas().clientWidth
const height = map.getCanvas().clientHeight
console.log("Canvas size markers:", map.getCanvas().width, map.getCanvas().height, "canvasClientRect:", width, height)
map.getCanvas().style.display = "none"
const img = await htmltoimage.toCanvas(map.getCanvasContainer(), {
pixelRatio: dpiFactor,
canvasWidth: width,
canvasHeight: height,
width: width,
height: height,
})
map.getCanvas().style.display = "unset"
return img
}
private updateStores(isSetup: boolean = false): void {

View file

@ -28,7 +28,7 @@
import LoginToggle from "./Base/LoginToggle.svelte";
import LoginButton from "./Base/LoginButton.svelte";
import CopyrightPanel from "./BigComponents/CopyrightPanel";
import {DownloadPanel} from "./BigComponents/DownloadPanel";
import DownloadPanel from "./DownloadFlow/DownloadPanel.svelte";
import ModalRight from "./Base/ModalRight.svelte";
import {Utils} from "../Utils";
import Hotkeys from "./Base/Hotkeys";
@ -42,10 +42,10 @@
import {ShareScreen} from "./BigComponents/ShareScreen";
import ThemeIntroPanel from "./BigComponents/ThemeIntroPanel.svelte";
import type {RasterLayerPolygon} from "../Models/RasterLayers";
import {AvailableRasterLayers} from "../Models/RasterLayers";
import RasterLayerOverview from "./Map/RasterLayerOverview.svelte";
import IfHidden from "./Base/IfHidden.svelte";
import {onDestroy} from "svelte";
import {AvailableRasterLayers} from "../Models/RasterLayers";
export let state: ThemeViewState;
let layout = state.layout;
@ -244,7 +244,7 @@
</If>
</div>
<div class="m-4" slot="content2">
<ToSvelte construct={() => new DownloadPanel(state)}/>
<DownloadPanel {state}/>
</div>
<div slot="title3">