@celljs/ta-geo 4.30.0 → 4.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -7,5 +7,7 @@ Real places for Ta's extensions (a plain library, not a pi package), for any ext
7
7
  - **A source of tiles** (`OpenFreeMapTiles`): OpenStreetMap, free and without a key, under versions whose URLs never change.
8
8
  - **Places** (`GeoPlaces`): a search of Nominatim, the name of a place, the location of the browser.
9
9
  - **The ground of a plot** (`GeoRaster`): a kind of ground for each column and the buildings with their heights.
10
+ - **How high the ground is** (`GeoElevation`): heights at the points of one lattice over the earth (5 × 5 a plot, one request), the lowest of the nine round each to take away buildings and trees, less the low ground of the region; plots side by side read the same points on their edge and fit. Open-Meteo (Copernicus DEM) by default, free and without a key.
11
+ - **The weather of a place** (`GeoWeather`): clear, cloudy, overcast, fog, rain, snow or a storm, how warm, the clouds, the wind, sunrise, sunset and the place's clock; kept a quarter of an hour for a square of about a kilometre, only the place sent.
10
12
 
11
13
  Map data © OpenStreetMap contributors: say so where it is shown (ODbL). The design is `docs/design/ta-earth.md`.
package/README.md CHANGED
@@ -7,5 +7,7 @@
7
7
  - **瓦片来源**(`OpenFreeMapTiles`):OpenStreetMap 数据,免费、无需密钥;瓦片地址带版本,永不变,所以同一版本在每台设备上一样。版本下架时退回最新版。
8
8
  - **地名搜索与定位**(`GeoPlaces`):Nominatim 搜索、反查地名,浏览器定位。
9
9
  - **地面栅格化**(`GeoRaster`):把一个地块上的地物画成每列一种地面(草、公园、树林、水、道路……)和建筑(轮廓、高度、颜色)。
10
+ - **地形高度**(`GeoElevation`):在全球统一的格点上读高度(每地块 5 × 5 个点,一次请求),每点取周围九点最低去掉楼和树,再减去区域低地基准,相邻地块边上读的是同一批点,拼起来不断。默认 Open-Meteo(Copernicus DEM),免费无密钥。
11
+ - **当地天气**(`GeoWeather`):晴、多云、阴、雾、雨、雪、雷雨,气温、云量、风、日出日落和当地时差;按约 1 公里的格子缓存 15 分钟,只发出位置。
10
12
 
11
13
  地图数据 © OpenStreetMap 贡献者,使用时界面上要写出来(ODbL)。设计见 `docs/design/ta-earth.md`。
@@ -0,0 +1,42 @@
1
+ import { type LonLat, type Plot } from './geo-grid.js';
2
+ import type { Fetcher } from './geo-tiles.js';
3
+ /** Columns between two points of the lattice: a quarter of a plot. */
4
+ export declare const RELIEF_STEP = 128;
5
+ export interface ElevationSource {
6
+ /** The height above the sea of each place, in metres. */
7
+ read(places: LonLat[]): Promise<number[]>;
8
+ }
9
+ export declare class OpenMeteoElevation implements ElevationSource {
10
+ protected readonly fetcher: Fetcher;
11
+ protected readonly base: string;
12
+ constructor(fetcher?: Fetcher, base?: string);
13
+ read(places: LonLat[]): Promise<number[]>;
14
+ }
15
+ /** The ground of a plot: metres above the low ground of its region. */
16
+ export interface PlotRelief {
17
+ /** At the points of the lattice on and in the plot, (PER_PLOT + 1)² of them, row by row from the north-west. */
18
+ readonly lattice: Float32Array;
19
+ /** At a column of the plot (0 to 511 each way), between the points round it. */
20
+ at(x: number, z: number): number;
21
+ }
22
+ interface Waiting {
23
+ ix: number;
24
+ iz: number;
25
+ resolve(metres: number): void;
26
+ reject(error: unknown): void;
27
+ }
28
+ export declare class GeoElevation {
29
+ protected readonly source: ElevationSource;
30
+ protected readonly points: Map<string, Promise<number>>;
31
+ protected waiting: Waiting[];
32
+ protected timer?: ReturnType<typeof setTimeout>;
33
+ constructor(source?: ElevationSource);
34
+ /** The ground of a plot; it fails when the heights cannot be read (the next time asks again). */
35
+ plot({ px, pz }: Plot): Promise<PlotRelief>;
36
+ /** The ground between the points of a lattice of a plot. */
37
+ static relief(lattice: Float32Array): PlotRelief;
38
+ /** The height of a point of the lattice, read with others asked at the same time. */
39
+ protected point(ix: number, iz: number): Promise<number>;
40
+ protected flush(): void;
41
+ }
42
+ export {};
@@ -0,0 +1,165 @@
1
+ import { GeoGrid, PLOT_SIZE } from './geo-grid.js';
2
+ // How high the ground is (GeoElevation): heights read at the points of one lattice over the whole earth, a point
3
+ // every RELIEF_STEP columns, so that two plots side by side read the same points on their edge and fit; of each
4
+ // point the lowest of it and the eight round it, which takes away the buildings and trees the model of the
5
+ // surface has in it and leaves the hills; then less a datum, the low ground of the region (the lowest of nine
6
+ // points round each corner of a much coarser lattice, between them in a straight line), so that a city by the sea
7
+ // and one on a plateau both stand on their own ground. The same points give the same heights on every device: what
8
+ // each makes of a place, the others make too. Open-Meteo by default (Copernicus DEM, 90 m), free and without a key.
9
+ /** Columns between two points of the lattice: a quarter of a plot. */
10
+ export const RELIEF_STEP = 128;
11
+ /** Points of the lattice between two corners of the datum's (about 30 km at the equator). */
12
+ const DATUM_STEPS = 256;
13
+ const PER_PLOT = PLOT_SIZE / RELIEF_STEP;
14
+ /** Points asked in one request at most. */
15
+ const BATCH = 100;
16
+ /** Points kept, the latest read. */
17
+ const KEPT = 20000;
18
+ export class OpenMeteoElevation {
19
+ constructor(fetcher = (url, init) => fetch(url, init), base = 'https://api.open-meteo.com/v1/elevation') {
20
+ this.fetcher = fetcher;
21
+ this.base = base;
22
+ }
23
+ async read(places) {
24
+ const latitude = places.map(each => each.lat.toFixed(5)).join(',');
25
+ const longitude = places.map(each => each.lon.toFixed(5)).join(',');
26
+ const response = await this.fetcher(`${this.base}?latitude=${latitude}&longitude=${longitude}`);
27
+ if (!response.ok) {
28
+ throw new Error(`Elevation: HTTP ${response.status}`);
29
+ }
30
+ const json = (await response.json());
31
+ if (!Array.isArray(json.elevation) || json.elevation.length !== places.length) {
32
+ throw new Error('Elevation: no heights');
33
+ }
34
+ return json.elevation.map(value => (typeof value === 'number' && Number.isFinite(value) ? value : 0));
35
+ }
36
+ }
37
+ export class GeoElevation {
38
+ constructor(source = new OpenMeteoElevation()) {
39
+ this.source = source;
40
+ this.points = new Map();
41
+ this.waiting = [];
42
+ }
43
+ /** The ground of a plot; it fails when the heights cannot be read (the next time asks again). */
44
+ async plot({ px, pz }) {
45
+ const ix0 = px * PER_PLOT;
46
+ const iz0 = pz * PER_PLOT;
47
+ const side = PER_PLOT + 1;
48
+ // Every point asked at once, so that they go in one request.
49
+ const raw = new Map();
50
+ const ask = (ix, iz) => {
51
+ const key = `${ix},${iz}`;
52
+ let known = raw.get(key);
53
+ if (!known) {
54
+ known = this.point(ix, iz);
55
+ raw.set(key, known);
56
+ }
57
+ return known;
58
+ };
59
+ for (let iz = iz0 - 1; iz <= iz0 + side; iz++) {
60
+ for (let ix = ix0 - 1; ix <= ix0 + side; ix++) {
61
+ ask(ix, iz);
62
+ }
63
+ }
64
+ const corners = new Map();
65
+ const corner = (jx, jz) => {
66
+ const key = `${jx},${jz}`;
67
+ let known = corners.get(key);
68
+ if (!known) {
69
+ const half = DATUM_STEPS / 2;
70
+ const nine = [];
71
+ for (let b = -1; b <= 1; b++) {
72
+ for (let a = -1; a <= 1; a++) {
73
+ nine.push(ask(jx * DATUM_STEPS + a * half, jz * DATUM_STEPS + b * half));
74
+ }
75
+ }
76
+ known = Promise.all(nine).then(values => Math.min(...values));
77
+ corners.set(key, known);
78
+ }
79
+ return known;
80
+ };
81
+ const lattice = new Float32Array(side * side);
82
+ const datums = [];
83
+ for (let iz = iz0; iz < iz0 + side; iz++) {
84
+ for (let ix = ix0; ix < ix0 + side; ix++) {
85
+ const jx = Math.floor(ix / DATUM_STEPS);
86
+ const jz = Math.floor(iz / DATUM_STEPS);
87
+ const tx = ix / DATUM_STEPS - jx;
88
+ const tz = iz / DATUM_STEPS - jz;
89
+ datums.push(Promise.all([corner(jx, jz), corner(jx + 1, jz), corner(jx, jz + 1), corner(jx + 1, jz + 1)]).then(([a, b, c, d]) => (a * (1 - tx) + b * tx) * (1 - tz) + (c * (1 - tx) + d * tx) * tz));
90
+ }
91
+ }
92
+ const [heights, datum] = await Promise.all([Promise.all([...raw.values()]), Promise.all(datums)]);
93
+ const keys = [...raw.keys()];
94
+ const metres = new Map(keys.map((key, k) => [key, heights[k]]));
95
+ const height = (ix, iz) => { var _a; return (_a = metres.get(`${ix},${iz}`)) !== null && _a !== void 0 ? _a : 0; };
96
+ for (let row = 0; row < side; row++) {
97
+ for (let col = 0; col < side; col++) {
98
+ let low = Number.POSITIVE_INFINITY;
99
+ for (let b = -1; b <= 1; b++) {
100
+ for (let a = -1; a <= 1; a++) {
101
+ low = Math.min(low, height(ix0 + col + a, iz0 + row + b));
102
+ }
103
+ }
104
+ lattice[row * side + col] = Math.max(0, low - datum[row * side + col]);
105
+ }
106
+ }
107
+ return GeoElevation.relief(lattice);
108
+ }
109
+ /** The ground between the points of a lattice of a plot. */
110
+ static relief(lattice) {
111
+ const side = PER_PLOT + 1;
112
+ return {
113
+ lattice,
114
+ at(x, z) {
115
+ const fx = Math.min(PER_PLOT - 1e-6, Math.max(0, (x + 0.5) / RELIEF_STEP));
116
+ const fz = Math.min(PER_PLOT - 1e-6, Math.max(0, (z + 0.5) / RELIEF_STEP));
117
+ const ix = Math.floor(fx);
118
+ const iz = Math.floor(fz);
119
+ const tx = fx - ix;
120
+ const tz = fz - iz;
121
+ const v = (c, r) => lattice[(iz + r) * side + ix + c];
122
+ return (v(0, 0) * (1 - tx) + v(1, 0) * tx) * (1 - tz) + (v(0, 1) * (1 - tx) + v(1, 1) * tx) * tz;
123
+ },
124
+ };
125
+ }
126
+ /** The height of a point of the lattice, read with others asked at the same time. */
127
+ point(ix, iz) {
128
+ const key = `${ix},${iz}`;
129
+ const known = this.points.get(key);
130
+ if (known) {
131
+ return known;
132
+ }
133
+ const made = new Promise((resolve, reject) => {
134
+ var _a;
135
+ this.waiting.push({ ix, iz, resolve, reject });
136
+ (_a = this.timer) !== null && _a !== void 0 ? _a : (this.timer = setTimeout(() => this.flush(), 0));
137
+ });
138
+ made.catch(() => this.points.delete(key));
139
+ this.points.set(key, made);
140
+ while (this.points.size > KEPT) {
141
+ this.points.delete(this.points.keys().next().value);
142
+ }
143
+ return made;
144
+ }
145
+ flush() {
146
+ this.timer = undefined;
147
+ const all = this.waiting;
148
+ this.waiting = [];
149
+ for (let start = 0; start < all.length; start += BATCH) {
150
+ const batch = all.slice(start, start + BATCH);
151
+ const places = batch.map(each => GeoGrid.toLonLat({ x: each.ix * RELIEF_STEP, z: each.iz * RELIEF_STEP }));
152
+ const read = (tries) => this.source.read(places).catch(error => (tries > 0 ? read(tries - 1) : Promise.reject(error)));
153
+ read(1).then(values => {
154
+ for (const [k, each] of batch.entries()) {
155
+ each.resolve(values[k]);
156
+ }
157
+ }, error => {
158
+ for (const each of batch) {
159
+ each.reject(error);
160
+ }
161
+ });
162
+ }
163
+ }
164
+ }
165
+ //# sourceMappingURL=geo-elevation.js.map
package/esm/geo-grid.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** The zoom of a plot. */
2
2
  export declare const PLOT_ZOOM = 16;
3
3
  /** Columns across a plot. */
4
- export declare const PLOT_SIZE = 256;
4
+ export declare const PLOT_SIZE = 512;
5
5
  /** The zoom of a column: a pixel of a plot. */
6
6
  export declare const COLUMN_ZOOM: number;
7
7
  export interface LonLat {
package/esm/geo-grid.js CHANGED
@@ -1,12 +1,13 @@
1
1
  // The earth as one grid (GeoGrid): Web Mercator, as the maps of the web draw it, cut into plots, the tiles of
2
- // zoom 16, each of 256 × 256 columns. A column is a pixel of zoom 24, so that every device names the same place by
3
- // the same numbers and what each makes of it fits beside what the others make, with nothing to agree on.
2
+ // zoom 16, each of 512 × 512 columns. A column is a pixel of zoom 25 (about a metre: 1.19 m at the equator, 1.1 m
3
+ // at 22°), so that every device names the same place by the same numbers and what each makes of it fits beside what
4
+ // the others make, with nothing to agree on.
4
5
  /** The zoom of a plot. */
5
6
  export const PLOT_ZOOM = 16;
6
7
  /** Columns across a plot. */
7
- export const PLOT_SIZE = 256;
8
+ export const PLOT_SIZE = 512;
8
9
  /** The zoom of a column: a pixel of a plot. */
9
- export const COLUMN_ZOOM = PLOT_ZOOM + 8;
10
+ export const COLUMN_ZOOM = PLOT_ZOOM + 9;
10
11
  const COLUMNS = 2 ** COLUMN_ZOOM;
11
12
  /** The earth's circumference at the equator, in metres (WGS 84). */
12
13
  const EQUATOR = 40075016.686;
@@ -9,6 +9,10 @@ export declare namespace GeoPlaces {
9
9
  function search(query: string, language: string, fetcher?: Fetcher): Promise<GeoPlace[]>;
10
10
  /** What a place is called: the name of what is there, or its street; none if the search knows nothing. */
11
11
  function name(place: LonLat, language: string, fetcher?: Fetcher): Promise<GeoPlace | undefined>;
12
- /** Where the device is, if the user lets the page know. */
13
- function here(timeout?: number): Promise<LonLat>;
12
+ /**
13
+ * Where the device is, if the user lets the page know. It fails with `denied` (the user or the system said no),
14
+ * `unavailable` or `timeout`; never waits longer than `deadline`, as a browser that cannot ask (an app without
15
+ * leave to use the location) may never answer, and its own timeout only starts once it is allowed.
16
+ */
17
+ function here(timeout?: number, deadline?: number): Promise<LonLat>;
14
18
  }
package/esm/geo-places.js CHANGED
@@ -55,15 +55,26 @@ export var GeoPlaces;
55
55
  return { ...place, name: called, detail };
56
56
  }
57
57
  GeoPlaces.name = name;
58
- /** Where the device is, if the user lets the page know. */
59
- function here(timeout = 15000) {
58
+ /**
59
+ * Where the device is, if the user lets the page know. It fails with `denied` (the user or the system said no),
60
+ * `unavailable` or `timeout`; never waits longer than `deadline`, as a browser that cannot ask (an app without
61
+ * leave to use the location) may never answer, and its own timeout only starts once it is allowed.
62
+ */
63
+ function here(timeout = 15000, deadline = 45000) {
60
64
  return new Promise((resolve, reject) => {
61
65
  const geo = typeof navigator === 'undefined' ? undefined : navigator.geolocation;
62
66
  if (!geo) {
63
- reject(new Error('location'));
67
+ reject(new Error('unavailable'));
64
68
  return;
65
69
  }
66
- geo.getCurrentPosition(position => resolve({ lon: position.coords.longitude, lat: position.coords.latitude }), error => reject(new Error(error.message || 'location')), { enableHighAccuracy: false, timeout, maximumAge: 600000 });
70
+ const timer = setTimeout(() => reject(new Error('timeout')), deadline);
71
+ geo.getCurrentPosition(position => {
72
+ clearTimeout(timer);
73
+ resolve({ lon: position.coords.longitude, lat: position.coords.latitude });
74
+ }, error => {
75
+ clearTimeout(timer);
76
+ reject(new Error(error.code === 1 ? 'denied' : error.code === 3 ? 'timeout' : 'unavailable'));
77
+ }, { enableHighAccuracy: false, timeout, maximumAge: 600000 });
67
78
  });
68
79
  }
69
80
  GeoPlaces.here = here;
@@ -45,9 +45,10 @@ type Ring = [number, number][];
45
45
  export declare namespace GeoRaster {
46
46
  /**
47
47
  * The ground of a plot from the layers of the tile it is in: `window` where in the tile, `metres` the metres
48
- * a column is across there (GeoGrid.metresPerColumn).
48
+ * a column is across there (GeoGrid.metresPerColumn); `size` columns across, fewer for a map seen from far (each
49
+ * then as many metres more).
49
50
  */
50
- function plot(layers: ReadonlyMap<string, MvtLayer> | undefined, window: PlotWindow, metres: number): PlotRaster;
51
+ function plot(layers: ReadonlyMap<string, MvtLayer> | undefined, window: PlotWindow, metres: number, size?: number): PlotRaster;
51
52
  /** Runs `set` on each column whose middle is inside the rings (even-odd). */
52
53
  function fill(rings: readonly Ring[], size: number, set: (index: number) => void): void;
53
54
  /** Runs `set` on each column whose middle is within `width / 2` of the line. */
package/esm/geo-raster.js CHANGED
@@ -61,10 +61,11 @@ export var GeoRaster;
61
61
  (function (GeoRaster) {
62
62
  /**
63
63
  * The ground of a plot from the layers of the tile it is in: `window` where in the tile, `metres` the metres
64
- * a column is across there (GeoGrid.metresPerColumn).
64
+ * a column is across there (GeoGrid.metresPerColumn); `size` columns across, fewer for a map seen from far (each
65
+ * then as many metres more).
65
66
  */
66
- function plot(layers, window, metres) {
67
- const size = PLOT_SIZE;
67
+ function plot(layers, window, metres, size = PLOT_SIZE) {
68
+ const across = metres * (PLOT_SIZE / size);
68
69
  const ground = new Uint8Array(size * size);
69
70
  const building = new Uint16Array(size * size);
70
71
  const buildings = [];
@@ -116,7 +117,7 @@ export var GeoRaster;
116
117
  const wide = WATERWAYS[String(feature.properties.class)];
117
118
  if (wide && feature.type === 2 && feature.properties.brunnel !== 'tunnel') {
118
119
  for (const part of parts) {
119
- stroke(part, Math.max(1, wide / metres), size, set(Ground.WATER));
120
+ stroke(part, Math.max(1, wide / across), size, set(Ground.WATER));
120
121
  }
121
122
  }
122
123
  });
@@ -126,7 +127,7 @@ export var GeoRaster;
126
127
  }
127
128
  else if (feature.type === 2) {
128
129
  for (const part of parts) {
129
- stroke(part, 40 / metres, size, set(Ground.PAVED));
130
+ stroke(part, 40 / across, size, set(Ground.PAVED));
130
131
  }
131
132
  }
132
133
  });
@@ -143,7 +144,7 @@ export var GeoRaster;
143
144
  return;
144
145
  }
145
146
  const footway = feature.properties.subclass === 'footway' || feature.properties.subclass === 'pedestrian';
146
- ways.push({ width: way.metres / metres, kind: footway ? Ground.PATH : way.ground, parts, area: feature.type === 3 });
147
+ ways.push({ width: way.metres / across, kind: footway ? Ground.PATH : way.ground, parts, area: feature.type === 3 });
147
148
  });
148
149
  ways.sort((a, b) => a.width - b.width);
149
150
  for (const way of ways) {
@@ -0,0 +1,42 @@
1
+ import type { LonLat } from './geo-grid.js';
2
+ import type { Fetcher } from './geo-tiles.js';
3
+ export type WeatherKind = 'clear' | 'cloudy' | 'overcast' | 'fog' | 'drizzle' | 'rain' | 'snow' | 'storm';
4
+ export interface GeoWeatherNow {
5
+ kind: WeatherKind;
6
+ /** The code of the World Meteorological Organization. */
7
+ code: number;
8
+ /** °C. */
9
+ temperature: number;
10
+ /** How much of the sky is cloud, 0 to 1. */
11
+ cloud: number;
12
+ /** Km/h. */
13
+ wind: number;
14
+ /** Mm in the last hour. */
15
+ precipitation: number;
16
+ /** Metres of snow on the ground. */
17
+ snowDepth: number;
18
+ day: boolean;
19
+ /** The hours of the place's clock the sun rises and sets at. */
20
+ sunrise: number;
21
+ sunset: number;
22
+ /** Seconds the place's clock is ahead of UTC. */
23
+ offset: number;
24
+ /** When it was read (ms). */
25
+ at: number;
26
+ }
27
+ export declare namespace GeoWeatherUtil {
28
+ function kindOf(code: number, cloud?: number): WeatherKind;
29
+ /** The hour of the place's clock (0 to 24). */
30
+ function hoursAt(offset: number, now?: number): number;
31
+ /** `2026-11-23T06:31` as hours (6.52); none for what is not a time. */
32
+ function hoursOf(local: unknown): number | undefined;
33
+ }
34
+ export declare class GeoWeather {
35
+ protected readonly fetcher: Fetcher;
36
+ protected readonly base: string;
37
+ protected readonly clock: () => number;
38
+ protected readonly kept: Map<string, Promise<GeoWeatherNow>>;
39
+ constructor(fetcher?: Fetcher, base?: string, clock?: () => number);
40
+ now(place: LonLat): Promise<GeoWeatherNow>;
41
+ protected read(key: string, lat: string, lon: string): Promise<GeoWeatherNow>;
42
+ }
@@ -0,0 +1,99 @@
1
+ /** Kept this long for the same square. */
2
+ const KEPT_MS = 15 * 60000;
3
+ export var GeoWeatherUtil;
4
+ (function (GeoWeatherUtil) {
5
+ function kindOf(code, cloud = 0) {
6
+ if (code >= 95) {
7
+ return 'storm';
8
+ }
9
+ if ((code >= 71 && code <= 77) || code === 85 || code === 86) {
10
+ return 'snow';
11
+ }
12
+ if ((code >= 61 && code <= 67) || (code >= 80 && code <= 82)) {
13
+ return 'rain';
14
+ }
15
+ if (code >= 51 && code <= 57) {
16
+ return 'drizzle';
17
+ }
18
+ if (code === 45 || code === 48) {
19
+ return 'fog';
20
+ }
21
+ if (code === 3 || cloud >= 0.85) {
22
+ return 'overcast';
23
+ }
24
+ return code === 2 || cloud >= 0.4 ? 'cloudy' : 'clear';
25
+ }
26
+ GeoWeatherUtil.kindOf = kindOf;
27
+ /** The hour of the place's clock (0 to 24). */
28
+ function hoursAt(offset, now = Date.now()) {
29
+ const seconds = now / 1000 + offset;
30
+ return (((seconds / 3600) % 24) + 24) % 24;
31
+ }
32
+ GeoWeatherUtil.hoursAt = hoursAt;
33
+ /** `2026-11-23T06:31` as hours (6.52); none for what is not a time. */
34
+ function hoursOf(local) {
35
+ const match = typeof local === 'string' ? /T(\d{2}):(\d{2})/.exec(local) : null;
36
+ return match ? Number(match[1]) + Number(match[2]) / 60 : undefined;
37
+ }
38
+ GeoWeatherUtil.hoursOf = hoursOf;
39
+ })(GeoWeatherUtil || (GeoWeatherUtil = {}));
40
+ export class GeoWeather {
41
+ constructor(fetcher = (url, init) => fetch(url, init), base = 'https://api.open-meteo.com/v1/forecast', clock = Date.now) {
42
+ this.fetcher = fetcher;
43
+ this.base = base;
44
+ this.clock = clock;
45
+ this.kept = new Map();
46
+ }
47
+ now(place) {
48
+ const lat = place.lat.toFixed(2);
49
+ const lon = place.lon.toFixed(2);
50
+ const key = `${lat},${lon}`;
51
+ const kept = this.kept.get(key);
52
+ if (kept) {
53
+ return kept.then(weather => (this.clock() - weather.at < KEPT_MS ? weather : this.read(key, lat, lon)));
54
+ }
55
+ return this.read(key, lat, lon);
56
+ }
57
+ read(key, lat, lon) {
58
+ const fields = 'temperature_2m,weather_code,cloud_cover,wind_speed_10m,precipitation,snow_depth,is_day';
59
+ const url = `${this.base}?latitude=${lat}&longitude=${lon}&current=${fields}&daily=sunrise,sunset&forecast_days=1&timezone=auto`;
60
+ const made = this.fetcher(url)
61
+ .then(response => {
62
+ if (!response.ok) {
63
+ throw new Error(`Weather: HTTP ${response.status}`);
64
+ }
65
+ return response.json();
66
+ })
67
+ .then(reply => {
68
+ var _a, _b, _c, _d;
69
+ var _e, _f, _g, _h, _j, _k, _l, _m;
70
+ const now = reply.current;
71
+ if (!now || typeof now.weather_code !== 'number') {
72
+ throw new Error('Weather: nothing now');
73
+ }
74
+ const cloud = Math.max(0, Math.min(1, ((_e = now.cloud_cover) !== null && _e !== void 0 ? _e : 0) / 100));
75
+ return {
76
+ kind: GeoWeatherUtil.kindOf(now.weather_code, cloud),
77
+ code: now.weather_code,
78
+ temperature: (_f = now.temperature_2m) !== null && _f !== void 0 ? _f : 0,
79
+ cloud,
80
+ wind: (_g = now.wind_speed_10m) !== null && _g !== void 0 ? _g : 0,
81
+ precipitation: (_h = now.precipitation) !== null && _h !== void 0 ? _h : 0,
82
+ snowDepth: (_j = now.snow_depth) !== null && _j !== void 0 ? _j : 0,
83
+ day: now.is_day !== 0,
84
+ sunrise: (_k = GeoWeatherUtil.hoursOf((_b = (_a = reply.daily) === null || _a === void 0 ? void 0 : _a.sunrise) === null || _b === void 0 ? void 0 : _b[0])) !== null && _k !== void 0 ? _k : 6,
85
+ sunset: (_l = GeoWeatherUtil.hoursOf((_d = (_c = reply.daily) === null || _c === void 0 ? void 0 : _c.sunset) === null || _d === void 0 ? void 0 : _d[0])) !== null && _l !== void 0 ? _l : 18.5,
86
+ offset: (_m = reply.utc_offset_seconds) !== null && _m !== void 0 ? _m : 0,
87
+ at: this.clock(),
88
+ };
89
+ });
90
+ made.catch(() => this.kept.delete(key));
91
+ this.kept.delete(key);
92
+ this.kept.set(key, made);
93
+ while (this.kept.size > 64) {
94
+ this.kept.delete(this.kept.keys().next().value);
95
+ }
96
+ return made;
97
+ }
98
+ }
99
+ //# sourceMappingURL=geo-weather.js.map
package/esm/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ export * from './geo-elevation.js';
1
2
  export * from './geo-grid.js';
2
3
  export * from './geo-mvt.js';
3
4
  export * from './geo-pixels.js';
4
5
  export * from './geo-places.js';
5
6
  export * from './geo-raster.js';
6
7
  export * from './geo-tiles.js';
8
+ export * from './geo-weather.js';
package/esm/index.js CHANGED
@@ -1,7 +1,9 @@
1
+ export * from './geo-elevation.js';
1
2
  export * from './geo-grid.js';
2
3
  export * from './geo-mvt.js';
3
4
  export * from './geo-pixels.js';
4
5
  export * from './geo-places.js';
5
6
  export * from './geo-raster.js';
6
7
  export * from './geo-tiles.js';
8
+ export * from './geo-weather.js';
7
9
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,43 @@
1
+ import { type LonLat, type Plot } from './geo-grid';
2
+ import type { Fetcher } from './geo-tiles';
3
+ /** Columns between two points of the lattice: a quarter of a plot. */
4
+ export declare const RELIEF_STEP = 128;
5
+ export interface ElevationSource {
6
+ /** The height above the sea of each place, in metres. */
7
+ read(places: LonLat[]): Promise<number[]>;
8
+ }
9
+ export declare class OpenMeteoElevation implements ElevationSource {
10
+ protected readonly fetcher: Fetcher;
11
+ protected readonly base: string;
12
+ constructor(fetcher?: Fetcher, base?: string);
13
+ read(places: LonLat[]): Promise<number[]>;
14
+ }
15
+ /** The ground of a plot: metres above the low ground of its region. */
16
+ export interface PlotRelief {
17
+ /** At the points of the lattice on and in the plot, (PER_PLOT + 1)² of them, row by row from the north-west. */
18
+ readonly lattice: Float32Array;
19
+ /** At a column of the plot (0 to 511 each way), between the points round it. */
20
+ at(x: number, z: number): number;
21
+ }
22
+ interface Waiting {
23
+ ix: number;
24
+ iz: number;
25
+ resolve(metres: number): void;
26
+ reject(error: unknown): void;
27
+ }
28
+ export declare class GeoElevation {
29
+ protected readonly source: ElevationSource;
30
+ protected readonly points: Map<string, Promise<number>>;
31
+ protected waiting: Waiting[];
32
+ protected timer?: ReturnType<typeof setTimeout>;
33
+ constructor(source?: ElevationSource);
34
+ /** The ground of a plot; it fails when the heights cannot be read (the next time asks again). */
35
+ plot({ px, pz }: Plot): Promise<PlotRelief>;
36
+ /** The ground between the points of a lattice of a plot. */
37
+ static relief(lattice: Float32Array): PlotRelief;
38
+ /** The height of a point of the lattice, read with others asked at the same time. */
39
+ protected point(ix: number, iz: number): Promise<number>;
40
+ protected flush(): void;
41
+ }
42
+ export {};
43
+ //# sourceMappingURL=geo-elevation.d.ts.map
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeoElevation = exports.OpenMeteoElevation = exports.RELIEF_STEP = void 0;
4
+ const geo_grid_1 = require("./geo-grid");
5
+ // How high the ground is (GeoElevation): heights read at the points of one lattice over the whole earth, a point
6
+ // every RELIEF_STEP columns, so that two plots side by side read the same points on their edge and fit; of each
7
+ // point the lowest of it and the eight round it, which takes away the buildings and trees the model of the
8
+ // surface has in it and leaves the hills; then less a datum, the low ground of the region (the lowest of nine
9
+ // points round each corner of a much coarser lattice, between them in a straight line), so that a city by the sea
10
+ // and one on a plateau both stand on their own ground. The same points give the same heights on every device: what
11
+ // each makes of a place, the others make too. Open-Meteo by default (Copernicus DEM, 90 m), free and without a key.
12
+ /** Columns between two points of the lattice: a quarter of a plot. */
13
+ exports.RELIEF_STEP = 128;
14
+ /** Points of the lattice between two corners of the datum's (about 30 km at the equator). */
15
+ const DATUM_STEPS = 256;
16
+ const PER_PLOT = geo_grid_1.PLOT_SIZE / exports.RELIEF_STEP;
17
+ /** Points asked in one request at most. */
18
+ const BATCH = 100;
19
+ /** Points kept, the latest read. */
20
+ const KEPT = 20000;
21
+ class OpenMeteoElevation {
22
+ constructor(fetcher = (url, init) => fetch(url, init), base = 'https://api.open-meteo.com/v1/elevation') {
23
+ this.fetcher = fetcher;
24
+ this.base = base;
25
+ }
26
+ async read(places) {
27
+ const latitude = places.map(each => each.lat.toFixed(5)).join(',');
28
+ const longitude = places.map(each => each.lon.toFixed(5)).join(',');
29
+ const response = await this.fetcher(`${this.base}?latitude=${latitude}&longitude=${longitude}`);
30
+ if (!response.ok) {
31
+ throw new Error(`Elevation: HTTP ${response.status}`);
32
+ }
33
+ const json = (await response.json());
34
+ if (!Array.isArray(json.elevation) || json.elevation.length !== places.length) {
35
+ throw new Error('Elevation: no heights');
36
+ }
37
+ return json.elevation.map(value => (typeof value === 'number' && Number.isFinite(value) ? value : 0));
38
+ }
39
+ }
40
+ exports.OpenMeteoElevation = OpenMeteoElevation;
41
+ class GeoElevation {
42
+ constructor(source = new OpenMeteoElevation()) {
43
+ this.source = source;
44
+ this.points = new Map();
45
+ this.waiting = [];
46
+ }
47
+ /** The ground of a plot; it fails when the heights cannot be read (the next time asks again). */
48
+ async plot({ px, pz }) {
49
+ const ix0 = px * PER_PLOT;
50
+ const iz0 = pz * PER_PLOT;
51
+ const side = PER_PLOT + 1;
52
+ // Every point asked at once, so that they go in one request.
53
+ const raw = new Map();
54
+ const ask = (ix, iz) => {
55
+ const key = `${ix},${iz}`;
56
+ let known = raw.get(key);
57
+ if (!known) {
58
+ known = this.point(ix, iz);
59
+ raw.set(key, known);
60
+ }
61
+ return known;
62
+ };
63
+ for (let iz = iz0 - 1; iz <= iz0 + side; iz++) {
64
+ for (let ix = ix0 - 1; ix <= ix0 + side; ix++) {
65
+ ask(ix, iz);
66
+ }
67
+ }
68
+ const corners = new Map();
69
+ const corner = (jx, jz) => {
70
+ const key = `${jx},${jz}`;
71
+ let known = corners.get(key);
72
+ if (!known) {
73
+ const half = DATUM_STEPS / 2;
74
+ const nine = [];
75
+ for (let b = -1; b <= 1; b++) {
76
+ for (let a = -1; a <= 1; a++) {
77
+ nine.push(ask(jx * DATUM_STEPS + a * half, jz * DATUM_STEPS + b * half));
78
+ }
79
+ }
80
+ known = Promise.all(nine).then(values => Math.min(...values));
81
+ corners.set(key, known);
82
+ }
83
+ return known;
84
+ };
85
+ const lattice = new Float32Array(side * side);
86
+ const datums = [];
87
+ for (let iz = iz0; iz < iz0 + side; iz++) {
88
+ for (let ix = ix0; ix < ix0 + side; ix++) {
89
+ const jx = Math.floor(ix / DATUM_STEPS);
90
+ const jz = Math.floor(iz / DATUM_STEPS);
91
+ const tx = ix / DATUM_STEPS - jx;
92
+ const tz = iz / DATUM_STEPS - jz;
93
+ datums.push(Promise.all([corner(jx, jz), corner(jx + 1, jz), corner(jx, jz + 1), corner(jx + 1, jz + 1)]).then(([a, b, c, d]) => (a * (1 - tx) + b * tx) * (1 - tz) + (c * (1 - tx) + d * tx) * tz));
94
+ }
95
+ }
96
+ const [heights, datum] = await Promise.all([Promise.all([...raw.values()]), Promise.all(datums)]);
97
+ const keys = [...raw.keys()];
98
+ const metres = new Map(keys.map((key, k) => [key, heights[k]]));
99
+ const height = (ix, iz) => { var _a; return (_a = metres.get(`${ix},${iz}`)) !== null && _a !== void 0 ? _a : 0; };
100
+ for (let row = 0; row < side; row++) {
101
+ for (let col = 0; col < side; col++) {
102
+ let low = Number.POSITIVE_INFINITY;
103
+ for (let b = -1; b <= 1; b++) {
104
+ for (let a = -1; a <= 1; a++) {
105
+ low = Math.min(low, height(ix0 + col + a, iz0 + row + b));
106
+ }
107
+ }
108
+ lattice[row * side + col] = Math.max(0, low - datum[row * side + col]);
109
+ }
110
+ }
111
+ return GeoElevation.relief(lattice);
112
+ }
113
+ /** The ground between the points of a lattice of a plot. */
114
+ static relief(lattice) {
115
+ const side = PER_PLOT + 1;
116
+ return {
117
+ lattice,
118
+ at(x, z) {
119
+ const fx = Math.min(PER_PLOT - 1e-6, Math.max(0, (x + 0.5) / exports.RELIEF_STEP));
120
+ const fz = Math.min(PER_PLOT - 1e-6, Math.max(0, (z + 0.5) / exports.RELIEF_STEP));
121
+ const ix = Math.floor(fx);
122
+ const iz = Math.floor(fz);
123
+ const tx = fx - ix;
124
+ const tz = fz - iz;
125
+ const v = (c, r) => lattice[(iz + r) * side + ix + c];
126
+ return (v(0, 0) * (1 - tx) + v(1, 0) * tx) * (1 - tz) + (v(0, 1) * (1 - tx) + v(1, 1) * tx) * tz;
127
+ },
128
+ };
129
+ }
130
+ /** The height of a point of the lattice, read with others asked at the same time. */
131
+ point(ix, iz) {
132
+ const key = `${ix},${iz}`;
133
+ const known = this.points.get(key);
134
+ if (known) {
135
+ return known;
136
+ }
137
+ const made = new Promise((resolve, reject) => {
138
+ var _a;
139
+ this.waiting.push({ ix, iz, resolve, reject });
140
+ (_a = this.timer) !== null && _a !== void 0 ? _a : (this.timer = setTimeout(() => this.flush(), 0));
141
+ });
142
+ made.catch(() => this.points.delete(key));
143
+ this.points.set(key, made);
144
+ while (this.points.size > KEPT) {
145
+ this.points.delete(this.points.keys().next().value);
146
+ }
147
+ return made;
148
+ }
149
+ flush() {
150
+ this.timer = undefined;
151
+ const all = this.waiting;
152
+ this.waiting = [];
153
+ for (let start = 0; start < all.length; start += BATCH) {
154
+ const batch = all.slice(start, start + BATCH);
155
+ const places = batch.map(each => geo_grid_1.GeoGrid.toLonLat({ x: each.ix * exports.RELIEF_STEP, z: each.iz * exports.RELIEF_STEP }));
156
+ const read = (tries) => this.source.read(places).catch(error => (tries > 0 ? read(tries - 1) : Promise.reject(error)));
157
+ read(1).then(values => {
158
+ for (const [k, each] of batch.entries()) {
159
+ each.resolve(values[k]);
160
+ }
161
+ }, error => {
162
+ for (const each of batch) {
163
+ each.reject(error);
164
+ }
165
+ });
166
+ }
167
+ }
168
+ }
169
+ exports.GeoElevation = GeoElevation;
170
+ //# sourceMappingURL=geo-elevation.js.map
package/lib/geo-grid.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** The zoom of a plot. */
2
2
  export declare const PLOT_ZOOM = 16;
3
3
  /** Columns across a plot. */
4
- export declare const PLOT_SIZE = 256;
4
+ export declare const PLOT_SIZE = 512;
5
5
  /** The zoom of a column: a pixel of a plot. */
6
6
  export declare const COLUMN_ZOOM: number;
7
7
  export interface LonLat {
package/lib/geo-grid.js CHANGED
@@ -1,15 +1,16 @@
1
1
  "use strict";
2
2
  // The earth as one grid (GeoGrid): Web Mercator, as the maps of the web draw it, cut into plots, the tiles of
3
- // zoom 16, each of 256 × 256 columns. A column is a pixel of zoom 24, so that every device names the same place by
4
- // the same numbers and what each makes of it fits beside what the others make, with nothing to agree on.
3
+ // zoom 16, each of 512 × 512 columns. A column is a pixel of zoom 25 (about a metre: 1.19 m at the equator, 1.1 m
4
+ // at 22°), so that every device names the same place by the same numbers and what each makes of it fits beside what
5
+ // the others make, with nothing to agree on.
5
6
  Object.defineProperty(exports, "__esModule", { value: true });
6
7
  exports.GeoGrid = exports.COLUMN_ZOOM = exports.PLOT_SIZE = exports.PLOT_ZOOM = void 0;
7
8
  /** The zoom of a plot. */
8
9
  exports.PLOT_ZOOM = 16;
9
10
  /** Columns across a plot. */
10
- exports.PLOT_SIZE = 256;
11
+ exports.PLOT_SIZE = 512;
11
12
  /** The zoom of a column: a pixel of a plot. */
12
- exports.COLUMN_ZOOM = exports.PLOT_ZOOM + 8;
13
+ exports.COLUMN_ZOOM = exports.PLOT_ZOOM + 9;
13
14
  const COLUMNS = 2 ** exports.COLUMN_ZOOM;
14
15
  /** The earth's circumference at the equator, in metres (WGS 84). */
15
16
  const EQUATOR = 40075016.686;
@@ -9,7 +9,11 @@ export declare namespace GeoPlaces {
9
9
  function search(query: string, language: string, fetcher?: Fetcher): Promise<GeoPlace[]>;
10
10
  /** What a place is called: the name of what is there, or its street; none if the search knows nothing. */
11
11
  function name(place: LonLat, language: string, fetcher?: Fetcher): Promise<GeoPlace | undefined>;
12
- /** Where the device is, if the user lets the page know. */
13
- function here(timeout?: number): Promise<LonLat>;
12
+ /**
13
+ * Where the device is, if the user lets the page know. It fails with `denied` (the user or the system said no),
14
+ * `unavailable` or `timeout`; never waits longer than `deadline`, as a browser that cannot ask (an app without
15
+ * leave to use the location) may never answer, and its own timeout only starts once it is allowed.
16
+ */
17
+ function here(timeout?: number, deadline?: number): Promise<LonLat>;
14
18
  }
15
19
  //# sourceMappingURL=geo-places.d.ts.map
package/lib/geo-places.js CHANGED
@@ -58,15 +58,26 @@ var GeoPlaces;
58
58
  return { ...place, name: called, detail };
59
59
  }
60
60
  GeoPlaces.name = name;
61
- /** Where the device is, if the user lets the page know. */
62
- function here(timeout = 15000) {
61
+ /**
62
+ * Where the device is, if the user lets the page know. It fails with `denied` (the user or the system said no),
63
+ * `unavailable` or `timeout`; never waits longer than `deadline`, as a browser that cannot ask (an app without
64
+ * leave to use the location) may never answer, and its own timeout only starts once it is allowed.
65
+ */
66
+ function here(timeout = 15000, deadline = 45000) {
63
67
  return new Promise((resolve, reject) => {
64
68
  const geo = typeof navigator === 'undefined' ? undefined : navigator.geolocation;
65
69
  if (!geo) {
66
- reject(new Error('location'));
70
+ reject(new Error('unavailable'));
67
71
  return;
68
72
  }
69
- geo.getCurrentPosition(position => resolve({ lon: position.coords.longitude, lat: position.coords.latitude }), error => reject(new Error(error.message || 'location')), { enableHighAccuracy: false, timeout, maximumAge: 600000 });
73
+ const timer = setTimeout(() => reject(new Error('timeout')), deadline);
74
+ geo.getCurrentPosition(position => {
75
+ clearTimeout(timer);
76
+ resolve({ lon: position.coords.longitude, lat: position.coords.latitude });
77
+ }, error => {
78
+ clearTimeout(timer);
79
+ reject(new Error(error.code === 1 ? 'denied' : error.code === 3 ? 'timeout' : 'unavailable'));
80
+ }, { enableHighAccuracy: false, timeout, maximumAge: 600000 });
70
81
  });
71
82
  }
72
83
  GeoPlaces.here = here;
@@ -45,9 +45,10 @@ type Ring = [number, number][];
45
45
  export declare namespace GeoRaster {
46
46
  /**
47
47
  * The ground of a plot from the layers of the tile it is in: `window` where in the tile, `metres` the metres
48
- * a column is across there (GeoGrid.metresPerColumn).
48
+ * a column is across there (GeoGrid.metresPerColumn); `size` columns across, fewer for a map seen from far (each
49
+ * then as many metres more).
49
50
  */
50
- function plot(layers: ReadonlyMap<string, MvtLayer> | undefined, window: PlotWindow, metres: number): PlotRaster;
51
+ function plot(layers: ReadonlyMap<string, MvtLayer> | undefined, window: PlotWindow, metres: number, size?: number): PlotRaster;
51
52
  /** Runs `set` on each column whose middle is inside the rings (even-odd). */
52
53
  function fill(rings: readonly Ring[], size: number, set: (index: number) => void): void;
53
54
  /** Runs `set` on each column whose middle is within `width / 2` of the line. */
package/lib/geo-raster.js CHANGED
@@ -64,10 +64,11 @@ var GeoRaster;
64
64
  (function (GeoRaster) {
65
65
  /**
66
66
  * The ground of a plot from the layers of the tile it is in: `window` where in the tile, `metres` the metres
67
- * a column is across there (GeoGrid.metresPerColumn).
67
+ * a column is across there (GeoGrid.metresPerColumn); `size` columns across, fewer for a map seen from far (each
68
+ * then as many metres more).
68
69
  */
69
- function plot(layers, window, metres) {
70
- const size = geo_grid_1.PLOT_SIZE;
70
+ function plot(layers, window, metres, size = geo_grid_1.PLOT_SIZE) {
71
+ const across = metres * (geo_grid_1.PLOT_SIZE / size);
71
72
  const ground = new Uint8Array(size * size);
72
73
  const building = new Uint16Array(size * size);
73
74
  const buildings = [];
@@ -119,7 +120,7 @@ var GeoRaster;
119
120
  const wide = WATERWAYS[String(feature.properties.class)];
120
121
  if (wide && feature.type === 2 && feature.properties.brunnel !== 'tunnel') {
121
122
  for (const part of parts) {
122
- stroke(part, Math.max(1, wide / metres), size, set(exports.Ground.WATER));
123
+ stroke(part, Math.max(1, wide / across), size, set(exports.Ground.WATER));
123
124
  }
124
125
  }
125
126
  });
@@ -129,7 +130,7 @@ var GeoRaster;
129
130
  }
130
131
  else if (feature.type === 2) {
131
132
  for (const part of parts) {
132
- stroke(part, 40 / metres, size, set(exports.Ground.PAVED));
133
+ stroke(part, 40 / across, size, set(exports.Ground.PAVED));
133
134
  }
134
135
  }
135
136
  });
@@ -146,7 +147,7 @@ var GeoRaster;
146
147
  return;
147
148
  }
148
149
  const footway = feature.properties.subclass === 'footway' || feature.properties.subclass === 'pedestrian';
149
- ways.push({ width: way.metres / metres, kind: footway ? exports.Ground.PATH : way.ground, parts, area: feature.type === 3 });
150
+ ways.push({ width: way.metres / across, kind: footway ? exports.Ground.PATH : way.ground, parts, area: feature.type === 3 });
150
151
  });
151
152
  ways.sort((a, b) => a.width - b.width);
152
153
  for (const way of ways) {
@@ -0,0 +1,43 @@
1
+ import type { LonLat } from './geo-grid';
2
+ import type { Fetcher } from './geo-tiles';
3
+ export type WeatherKind = 'clear' | 'cloudy' | 'overcast' | 'fog' | 'drizzle' | 'rain' | 'snow' | 'storm';
4
+ export interface GeoWeatherNow {
5
+ kind: WeatherKind;
6
+ /** The code of the World Meteorological Organization. */
7
+ code: number;
8
+ /** °C. */
9
+ temperature: number;
10
+ /** How much of the sky is cloud, 0 to 1. */
11
+ cloud: number;
12
+ /** Km/h. */
13
+ wind: number;
14
+ /** Mm in the last hour. */
15
+ precipitation: number;
16
+ /** Metres of snow on the ground. */
17
+ snowDepth: number;
18
+ day: boolean;
19
+ /** The hours of the place's clock the sun rises and sets at. */
20
+ sunrise: number;
21
+ sunset: number;
22
+ /** Seconds the place's clock is ahead of UTC. */
23
+ offset: number;
24
+ /** When it was read (ms). */
25
+ at: number;
26
+ }
27
+ export declare namespace GeoWeatherUtil {
28
+ function kindOf(code: number, cloud?: number): WeatherKind;
29
+ /** The hour of the place's clock (0 to 24). */
30
+ function hoursAt(offset: number, now?: number): number;
31
+ /** `2026-11-23T06:31` as hours (6.52); none for what is not a time. */
32
+ function hoursOf(local: unknown): number | undefined;
33
+ }
34
+ export declare class GeoWeather {
35
+ protected readonly fetcher: Fetcher;
36
+ protected readonly base: string;
37
+ protected readonly clock: () => number;
38
+ protected readonly kept: Map<string, Promise<GeoWeatherNow>>;
39
+ constructor(fetcher?: Fetcher, base?: string, clock?: () => number);
40
+ now(place: LonLat): Promise<GeoWeatherNow>;
41
+ protected read(key: string, lat: string, lon: string): Promise<GeoWeatherNow>;
42
+ }
43
+ //# sourceMappingURL=geo-weather.d.ts.map
@@ -0,0 +1,103 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GeoWeather = exports.GeoWeatherUtil = void 0;
4
+ /** Kept this long for the same square. */
5
+ const KEPT_MS = 15 * 60000;
6
+ var GeoWeatherUtil;
7
+ (function (GeoWeatherUtil) {
8
+ function kindOf(code, cloud = 0) {
9
+ if (code >= 95) {
10
+ return 'storm';
11
+ }
12
+ if ((code >= 71 && code <= 77) || code === 85 || code === 86) {
13
+ return 'snow';
14
+ }
15
+ if ((code >= 61 && code <= 67) || (code >= 80 && code <= 82)) {
16
+ return 'rain';
17
+ }
18
+ if (code >= 51 && code <= 57) {
19
+ return 'drizzle';
20
+ }
21
+ if (code === 45 || code === 48) {
22
+ return 'fog';
23
+ }
24
+ if (code === 3 || cloud >= 0.85) {
25
+ return 'overcast';
26
+ }
27
+ return code === 2 || cloud >= 0.4 ? 'cloudy' : 'clear';
28
+ }
29
+ GeoWeatherUtil.kindOf = kindOf;
30
+ /** The hour of the place's clock (0 to 24). */
31
+ function hoursAt(offset, now = Date.now()) {
32
+ const seconds = now / 1000 + offset;
33
+ return (((seconds / 3600) % 24) + 24) % 24;
34
+ }
35
+ GeoWeatherUtil.hoursAt = hoursAt;
36
+ /** `2026-11-23T06:31` as hours (6.52); none for what is not a time. */
37
+ function hoursOf(local) {
38
+ const match = typeof local === 'string' ? /T(\d{2}):(\d{2})/.exec(local) : null;
39
+ return match ? Number(match[1]) + Number(match[2]) / 60 : undefined;
40
+ }
41
+ GeoWeatherUtil.hoursOf = hoursOf;
42
+ })(GeoWeatherUtil || (exports.GeoWeatherUtil = GeoWeatherUtil = {}));
43
+ class GeoWeather {
44
+ constructor(fetcher = (url, init) => fetch(url, init), base = 'https://api.open-meteo.com/v1/forecast', clock = Date.now) {
45
+ this.fetcher = fetcher;
46
+ this.base = base;
47
+ this.clock = clock;
48
+ this.kept = new Map();
49
+ }
50
+ now(place) {
51
+ const lat = place.lat.toFixed(2);
52
+ const lon = place.lon.toFixed(2);
53
+ const key = `${lat},${lon}`;
54
+ const kept = this.kept.get(key);
55
+ if (kept) {
56
+ return kept.then(weather => (this.clock() - weather.at < KEPT_MS ? weather : this.read(key, lat, lon)));
57
+ }
58
+ return this.read(key, lat, lon);
59
+ }
60
+ read(key, lat, lon) {
61
+ const fields = 'temperature_2m,weather_code,cloud_cover,wind_speed_10m,precipitation,snow_depth,is_day';
62
+ const url = `${this.base}?latitude=${lat}&longitude=${lon}&current=${fields}&daily=sunrise,sunset&forecast_days=1&timezone=auto`;
63
+ const made = this.fetcher(url)
64
+ .then(response => {
65
+ if (!response.ok) {
66
+ throw new Error(`Weather: HTTP ${response.status}`);
67
+ }
68
+ return response.json();
69
+ })
70
+ .then(reply => {
71
+ var _a, _b, _c, _d;
72
+ var _e, _f, _g, _h, _j, _k, _l, _m;
73
+ const now = reply.current;
74
+ if (!now || typeof now.weather_code !== 'number') {
75
+ throw new Error('Weather: nothing now');
76
+ }
77
+ const cloud = Math.max(0, Math.min(1, ((_e = now.cloud_cover) !== null && _e !== void 0 ? _e : 0) / 100));
78
+ return {
79
+ kind: GeoWeatherUtil.kindOf(now.weather_code, cloud),
80
+ code: now.weather_code,
81
+ temperature: (_f = now.temperature_2m) !== null && _f !== void 0 ? _f : 0,
82
+ cloud,
83
+ wind: (_g = now.wind_speed_10m) !== null && _g !== void 0 ? _g : 0,
84
+ precipitation: (_h = now.precipitation) !== null && _h !== void 0 ? _h : 0,
85
+ snowDepth: (_j = now.snow_depth) !== null && _j !== void 0 ? _j : 0,
86
+ day: now.is_day !== 0,
87
+ sunrise: (_k = GeoWeatherUtil.hoursOf((_b = (_a = reply.daily) === null || _a === void 0 ? void 0 : _a.sunrise) === null || _b === void 0 ? void 0 : _b[0])) !== null && _k !== void 0 ? _k : 6,
88
+ sunset: (_l = GeoWeatherUtil.hoursOf((_d = (_c = reply.daily) === null || _c === void 0 ? void 0 : _c.sunset) === null || _d === void 0 ? void 0 : _d[0])) !== null && _l !== void 0 ? _l : 18.5,
89
+ offset: (_m = reply.utc_offset_seconds) !== null && _m !== void 0 ? _m : 0,
90
+ at: this.clock(),
91
+ };
92
+ });
93
+ made.catch(() => this.kept.delete(key));
94
+ this.kept.delete(key);
95
+ this.kept.set(key, made);
96
+ while (this.kept.size > 64) {
97
+ this.kept.delete(this.kept.keys().next().value);
98
+ }
99
+ return made;
100
+ }
101
+ }
102
+ exports.GeoWeather = GeoWeather;
103
+ //# sourceMappingURL=geo-weather.js.map
package/lib/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
+ export * from './geo-elevation';
1
2
  export * from './geo-grid';
2
3
  export * from './geo-mvt';
3
4
  export * from './geo-pixels';
4
5
  export * from './geo-places';
5
6
  export * from './geo-raster';
6
7
  export * from './geo-tiles';
8
+ export * from './geo-weather';
7
9
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -14,10 +14,12 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./geo-elevation"), exports);
17
18
  __exportStar(require("./geo-grid"), exports);
18
19
  __exportStar(require("./geo-mvt"), exports);
19
20
  __exportStar(require("./geo-pixels"), exports);
20
21
  __exportStar(require("./geo-places"), exports);
21
22
  __exportStar(require("./geo-raster"), exports);
22
23
  __exportStar(require("./geo-tiles"), exports);
24
+ __exportStar(require("./geo-weather"), exports);
23
25
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-geo",
3
- "version": "4.30.0",
3
+ "version": "4.31.0",
4
4
  "description": "Real places for Ta's extensions: a grid of plots over the earth, vector tiles of OpenStreetMap decoded, places searched, the device's location, and what is on the ground of a plot as a grid",
5
5
  "homepage": "https://github.com/cellbang/ta",
6
6
  "bugs": {