Skip to content

Commit

Permalink
Merge pull request #945 from ZeLonewolf/zlw-better-clip-script
Browse files Browse the repository at this point in the history
Improved render sample config
  • Loading branch information
ZeLonewolf authored Oct 7, 2023
2 parents 9efee5b + 700b04a commit 2cd228c
Show file tree
Hide file tree
Showing 7 changed files with 172 additions and 91 deletions.
9 changes: 6 additions & 3 deletions scripts/build.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { stat, copyFile, mkdir } from "node:fs/promises";
import { pathToFileURL } from "node:url";

import esbuild, { BuildContext, BuildOptions } from "esbuild";

Expand All @@ -26,15 +25,19 @@ const buildWith = async (
await mkdir("dist", { recursive: true });

await Promise.all(
["index.html", "shieldtest.html", "favicon.ico"].map((f) =>
["index.html", "bare_map.html", "shieldtest.html", "favicon.ico"].map((f) =>
copyFile(`src/${f}`, `dist/${f}`)
)
);

const localConfig = await maybeLocalConfig();

const options = {
entryPoints: ["src/americana.js", "src/shieldtest.js"],
entryPoints: [
"src/americana.js",
"src/bare_americana.js",
"src/shieldtest.js",
],
format: "esm",
bundle: true,
minify: true,
Expand Down
32 changes: 14 additions & 18 deletions scripts/generate_samples.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
import fs from "node:fs";
import { chromium } from "@playwright/test";
import type * as maplibre from "maplibre-gl";

// Declare a global augmentation for the Window interface
declare global {
interface Window {
map?: {
loaded: () => boolean;
};
map?: maplibre.Map;
}
}

type LocationClip = {
x: number;
y: number;
width: number;
height: number;
};

type SampleSpecification = {
/** location on the map, a string in the format "z/lat/lon" */
location: string;
/** name of this screenshot, used for the filename */
name: string;
/** Size in pixels of the clip */
viewport: {
/** Width of the clip */
width: number;
/** height of the clip */
height: number;
};
clip: LocationClip;
/** If true, include the Americana demo map controls in the screenshot */
controls?: boolean;
};

// Load list of locations to take map screenshots
Expand Down Expand Up @@ -58,18 +56,17 @@ for (const screenshot of screenshots) {
}

async function createImage(screenshot: SampleSpecification) {
await page.goto(`http://localhost:1776/#map=${screenshot.location}`);
const pagePath: string = screenshot.controls ? "" : "bare_map.html";

await page.goto(
`http://localhost:1776/${pagePath}#map=${screenshot.location}`
);

// Wait for map to load, then wait two more seconds for images, etc. to load.
try {
await page.waitForFunction(() => window.map?.loaded(), {
timeout: 3000,
});

// Wait for 1.5 seconds on 3D model examples, since this takes longer to load.
const waitTime = 1500;
console.log(`waiting for ${waitTime} ms`);
await page.waitForTimeout(waitTime);
} catch (e) {
console.log(`Timed out waiting for map load`);
}
Expand All @@ -78,7 +75,6 @@ async function createImage(screenshot: SampleSpecification) {
await page.screenshot({
path: `${sampleFolder}/${screenshot.name}.png`,
type: "png",
clip: screenshot.clip,
});
console.log(`Created ${sampleFolder}/${screenshot.name}.png`);
} catch (err) {
Expand Down
59 changes: 7 additions & 52 deletions src/americana.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
import config from "./config.js";

import * as Label from "./constants/label.js";
import * as Style from "./js/style.js";

import * as Poi from "./js/poi.js";

import * as languageLabel from "./js/language_label.js";

Expand All @@ -17,26 +14,8 @@ import LegendControl from "./js/legend_control.js";
import * as LegendConfig from "./js/legend_config.js";
import SampleControl from "openmapsamples-maplibre/OpenMapSamplesControl.js";
import { default as OpenMapTilesSamples } from "openmapsamples/samples/OpenMapTiles/index.js";
import { URLShieldRenderer } from "@americana/maplibre-shield-generator";
import {
shieldPredicate,
networkPredicate,
routeParser,
} from "./js/shield_format.js";

export function buildStyle() {
var getUrl = window.location;
var baseUrl = (getUrl.protocol + "//" + getUrl.host + getUrl.pathname)
//Trim trailing slashes from URL
.replace(/\/+$/, "");
return Style.build(
config.OPENMAPTILES_URL,
`${baseUrl}/sprites/sprite`,
config.FONT_URL ??
"https://osm-americana.github.io/fontstack66/{fontstack}/{range}.pbf",
Label.getLocales()
);
}

import { createMap, loadRTLPlugin, buildStyle } from "./js/map_builder.js";

function upgradeLegacyHash() {
let hash = window.location.hash.substr(1);
Expand All @@ -47,22 +26,17 @@ function upgradeLegacyHash() {
}
upgradeLegacyHash();

maplibregl.setRTLTextPlugin(
"https://unpkg.com/@mapbox/[email protected]/mapbox-gl-rtl-text.min.js",
null,
true
);
loadRTLPlugin();

window.maplibregl = maplibregl;
export const map = (window.map = new maplibregl.Map({
export const map = createMap(window, (shields) => shieldDefLoad(shields), {
container: "map", // container id
hash: "map",
antialias: true,
style: buildStyle(),
center: [-94, 40.5], // starting position [lng, lat]
zoom: 4, // starting zoom
center: [-94, 40.5],
zoom: 4,
attributionControl: false,
}));
});

let options = {};

Expand All @@ -79,12 +53,6 @@ OpenMapTilesSamples.forEach((sample, i) => {

let legendControl;

const shieldRenderer = new URLShieldRenderer("shields.json", routeParser)
.filterImageID(shieldPredicate)
.filterNetwork(networkPredicate)
.renderOnMaplibreGL(map)
.onShieldDefLoad((shields) => shieldDefLoad(shields));

function shieldDefLoad(shields) {
legendControl = new LegendControl(shields);
legendControl.sections = LegendConfig.sections;
Expand Down Expand Up @@ -128,19 +96,6 @@ function shieldDefLoad(shields) {
}
}

map.on("styleimagemissing", function (e) {
switch (e.id.split("\n")[0]) {
case "shield":
break;
case "poi":
Poi.missingIconHandler(shieldRenderer, map, e);
break;
default:
console.warn("Image id not recognized:", JSON.stringify(e.id));
break;
}
});

function hotReloadMap() {
map.setStyle(buildStyle());
}
Expand Down
31 changes: 31 additions & 0 deletions src/bare_americana.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use strict";

import "maplibre-gl/dist/maplibre-gl.css";

import { createMap, loadRTLPlugin, buildStyle } from "./js/map_builder.js";

loadRTLPlugin();

export const map = createMap(window, (shields) => shieldDefLoad(), {
container: "map", // container id
hash: "map",
antialias: true,
style: buildStyle(),
center: [-94, 40.5],
zoom: 4,
fadeDuration: 0,
attributionControl: false,
});

function shieldDefLoad() {
if (window.top === window.self) {
// if not embedded in an iframe, autofocus canvas to enable keyboard shortcuts
map.getCanvas().focus();
}

if (window.LIVE_RELOAD) {
new EventSource("/esbuild").addEventListener("change", () =>
location.reload()
);
}
}
30 changes: 30 additions & 0 deletions src/bare_map.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>OpenStreetMap Americana</title>
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<style>
body {
margin: 0;
padding: 0;
}

#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
<script type="module" src="bare_americana.js"></script>
<link rel="stylesheet" href="americana.css" />
</head>

<body>
<div id="map"></div>
</body>
</html>
83 changes: 83 additions & 0 deletions src/js/map_builder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* Functions for assembling user-facing map components
*/
import {
ShieldDefinitions,
URLShieldRenderer,
} from "@americana/maplibre-shield-generator";
import config from "../config.js";

import {
shieldPredicate,
networkPredicate,
routeParser,
} from "../js/shield_format.js";

import * as Poi from "../js/poi.js";
import * as Label from "../constants/label.js";
import * as Style from "../js/style.js";
import maplibregl, { Map, MapOptions, StyleSpecification } from "maplibre-gl";

export function buildStyle(): StyleSpecification {
var getUrl = window.location;
var baseUrl = (
getUrl.protocol +
"//" +
getUrl.host +
removeAfterLastSlash(getUrl.pathname)
)
//Trim trailing slashes from URL
.replace(/\/+$/, "");
return Style.build(
config.OPENMAPTILES_URL,
`${baseUrl}/sprites/sprite`,
config.FONT_URL ??
"https://osm-americana.github.io/fontstack66/{fontstack}/{range}.pbf",
Label.getLocales()
);
}

function removeAfterLastSlash(str: string): string {
const lastSlashIndex = str.lastIndexOf("/");
if (lastSlashIndex === -1) {
return str; // return the original string if no slash is found
}
return str.substring(0, lastSlashIndex + 1);
}

export function loadRTLPlugin(): void {
maplibregl.setRTLTextPlugin(
"https://unpkg.com/@mapbox/[email protected]/mapbox-gl-rtl-text.min.js",
null,
true
);
}

export function createMap(
window,
shieldDefCallback: (shields: ShieldDefinitions) => void,
options: MapOptions
): Map {
window.maplibregl = maplibregl;
let map: Map = (window.map = new maplibregl.Map(options));

const shieldRenderer = new URLShieldRenderer("shields.json", routeParser)
.filterImageID(shieldPredicate)
.filterNetwork(networkPredicate)
.renderOnMaplibreGL(map)
.onShieldDefLoad(shieldDefCallback);

map.on("styleimagemissing", function (e) {
switch (e.id.split("\n")[0]) {
case "shield":
break;
case "poi":
Poi.missingIconHandler(shieldRenderer, map, e);
break;
default:
console.warn("Image id not recognized:", JSON.stringify(e.id));
break;
}
});
return map;
}
19 changes: 1 addition & 18 deletions test/sample_locations.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,14 @@
"width": 600,
"height": 250
},
"clip": {
"x": 0,
"y": 0,
"width": 600,
"height": 250
}
"controls": true
},
{
"location": "13/40.01264/-75.70446",
"name": "downingtown_alt_trk_bus",
"viewport": {
"width": 600,
"height": 600
},
"clip": {
"x": 100,
"y": 100,
"width": 400,
"height": 400
}
},
{
Expand All @@ -33,12 +22,6 @@
"viewport": {
"width": 600,
"height": 600
},
"clip": {
"x": 100,
"y": 100,
"width": 400,
"height": 400
}
}
]

0 comments on commit 2cd228c

Please sign in to comment.