@trailstash/ultra
Version:
A web based tool for making MapLibre GL maps with data from sources such as Overpass, GeoJSON, GPX, KML, TCX, etc
93 lines (82 loc) • 2.74 kB
JavaScript
import path from "path";
import fs from "fs";
import puppeteer from "puppeteer";
import minimist from "minimist";
const {
_: [exampleName],
useLocalhost,
height,
width,
waitTime,
output,
} = minimist(process.argv.slice(2));
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
// set viewport and double deviceScaleFactor to get a closer shot of the map
await page.setViewport({
width: width || 600,
height: height || 250,
deviceScaleFactor: 2,
});
async function createImage(exampleName) {
if (!output && !fs.existsSync(`./docs/assets/${path.dirname(exampleName)}`)) {
fs.mkdirSync(`./docs/assets/${path.dirname(exampleName)}`);
}
// get the example contents
const query = fs.readFileSync(exampleName, "utf-8");
if (useLocalhost) {
await page.goto(
`http://localhost:8000/#map&query=${encodeURIComponent(query)}`,
);
} else {
await page.goto(
`https://overpass-ultra.us/#map&query=${encodeURIComponent(query)}`,
);
}
// Wait for map to load, then wait two more seconds for images, etc. to load.
try {
//await page.waitForFunction('map.loaded()');
console.log(`waiting for ${waitTime || 4000} ms`);
await new Promise((resolve) => setTimeout(resolve, waitTime || 4000));
} catch (err) {
// map.loaded() does not evaluate to true within 3 seconds, it's probably an animated example.
// In this case we take the screenshot immediately.
console.log(`Timed out waiting for map load on ${exampleName}.`);
}
const filename =
output || `./docs/assets/${exampleName.replace(".ultra", ".png")}`;
await page
.screenshot({
path: filename,
type: "png",
clip: {
x: 0,
y: 0,
width: width || 600,
height: height || 250,
},
})
.then(() => console.log(`Created ${filename}`))
.catch((err) => {
console.log(err);
});
}
if (exampleName.endsWith("/")) {
const allFiles = fs
.readdirSync(exampleName)
.filter((f) => f.endsWith(".ultra"));
console.log(`Generating ${allFiles.length} images.`);
for (const file of allFiles) {
await createImage(path.join(exampleName, file));
}
} else if (exampleName) {
await createImage(exampleName);
} else {
throw new Error(`
Usage: npm run generate-images <file-name|all> [serve]
file-name: the name of the example file in test/examples without the .html extension.
all: generate images for all examples.
serve: use localhost to serve examples - use 'npm run start' with this option, otherwise it will use the latest published version in npm.
Example: npm run build:examples-images MapLibre-Examples/3d-buildings serve`);
}
await browser.close();