@tinkatinka/static-map 1.4.4

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/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ (The MIT License)
2
+
3
+ Copyright (c) 2021 TinkaTinka
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the 'Software'), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
package/README.md ADDED
@@ -0,0 +1,202 @@
1
+ # static-map
2
+ A node library to generate static map images.
3
+
4
+ ## Acknowledgements
5
+ The code is heavily inspired by the python-based library [staticmap](https://github.com/komoot/staticmap).
6
+
7
+ To generate the final image [node-canvas](https://github.com/Automattic/node-canvas) is being used.
8
+
9
+ ## Installation
10
+ ```bash
11
+ $ npm install @tinkatinka/static-map
12
+ ```
13
+
14
+ ## Usage
15
+ ```ts
16
+ import { StaticMap } from '@tinkatinka/static-map';
17
+ const map = new StaticMap(...);
18
+ ```
19
+ The constructor can be called with an optional `StaticMapOptions` object, overriding the defaults:
20
+
21
+ ```ts
22
+ {
23
+ width: number; // width of the image in pixels [default: 512]
24
+ height: number; // height of the image in pixels [default: 512]
25
+ padding: number; // padding in pixels [default: 0]
26
+ paddingX?: number; // horizontal padding (overrides `padding`)
27
+ paddingY?: number; // vertical padding (overrides `paddings`)
28
+ paddingLeft?: number; // left padding (overrides `paddingX`)
29
+ paddingRight?: number; // right padding (overrides `paddingX`)
30
+ paddingTop?: number; // top padding (overrides `paddingY`)
31
+ paddingBottom?: number; // bottom padding (overrides `paddingY`)
32
+ extent?: LatLngBounds; // extent of the map [default: `undefined`]
33
+ scaling: boolean; // scale image to match size and padding exactly [default: `true`]
34
+ tileURL: string; // template string for tile URL [default: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png']
35
+ tileSize: number; // size of tiles [default: 256]
36
+ tileMaxZoom: number; // maximum zoom available for tiles [default: 20]
37
+ tileCache?: string; // path to a cache directory for tiles [default: `undefined`]
38
+ backgroundColor?: string; // image background color (CSS string) [default: `undefined`]
39
+ grayscale: boolean; // apply a grayscale filter to map tiles (not overlays) [default: `false`]
40
+ }
41
+ ```
42
+ **Note**: Either an explicit `extent` of the map *or* at least one overlay (see below) **must** be defined,
43
+ otherwise the image generation will fail.
44
+
45
+ ### Types
46
+
47
+ #### LatLng
48
+ ```ts
49
+ {
50
+ lat: number; // latitude
51
+ lng: number; // longitude
52
+ }
53
+ ```
54
+
55
+ #### LatLngBounds
56
+ ```ts
57
+ {
58
+ min: LatLng; // minimum point
59
+ max: LatLng; // maximum point
60
+ }
61
+ ```
62
+
63
+ ### Overlays
64
+
65
+ #### Lines
66
+ ```ts
67
+ .addLine(src: LatLng, dst: LatLng, options?: Partial<StaticMapLineOptions>);
68
+
69
+ .addLines(points: LatLng[], options?: Partial<StaticMapLineOptions>);
70
+ ```
71
+
72
+ Options:
73
+
74
+ ```ts
75
+ interface StaticMapLineOptions {
76
+ strokeStyle: string; // css stroke style [default: 'black']
77
+ lineWidth: number; // line width in pixels [default: 1.0]
78
+ lineCap: 'butt' | 'round' | 'square' // [default: 'round']
79
+ lineJoin: 'bevel' | 'round' | 'miter' // [default: 'round']
80
+ }
81
+ ```
82
+
83
+ #### Circles
84
+ ```ts
85
+ .addCircle(center: LatLng, options?: Partial<StaticMapCircleOptions>);
86
+ ```
87
+
88
+ Options:
89
+
90
+ ```ts
91
+ interface StaticMapCircleOptions {
92
+ radius: number; // in pixels [default: 5.0]
93
+ strokeStyle?: string; // css stroke style or undefined for no stroke [default: 'black']
94
+ lineWidth: number; // line width in pixels [default: 1.0]
95
+ fillStyle?: string; // css fill style or undefined for no fill [default: 'rgba(0, 0, 0, 0.3)']
96
+ }
97
+ ```
98
+
99
+ #### Text
100
+ ```ts
101
+ .addText(text: string, anchor: LatLng, options?: Partial<StaticMapTextOptions>);
102
+ ```
103
+
104
+ Options:
105
+
106
+ ```ts
107
+ interface StaticMapTextOptions {
108
+ px: number; // padding x [default: 0]
109
+ py: number; // padding y [default: 0]
110
+ maxWidth?: number; // text max width [default: undefined]
111
+ direction: string; // default: 'ltr'
112
+ font: string; // default: '12px sans-serif'
113
+ textAlign: string; // default: 'center'
114
+ textBaseline: string; // default: 'middle'
115
+ strokeStyle?: string; // css stroke style or undefined for no stroke [default: undefined]
116
+ lineWidth: number; // line width in pixels [default: 1.0]
117
+ fillStyle?: string; // css fill style or undefined for no fill [default: 'black']
118
+ }
119
+ ```
120
+
121
+ #### Images
122
+ ```ts
123
+ .addImage(src: string, bounds: LatLngBounds);
124
+ ```
125
+
126
+ ### Output
127
+ Can be obtained via async functions
128
+
129
+ ```ts
130
+ .renderToDataURL(): Promise<string>
131
+
132
+ .renderToBuffer(): Promise<Buffer>
133
+
134
+ .renderToCanvas(): Promise<Canvas>
135
+ ```
136
+
137
+ All of them will fail if the `.extent` of the map is not explicitly defined or cannot be computed (because there are
138
+ no overlays).
139
+
140
+ ## Examples
141
+
142
+ ### with explicit extent
143
+ ```ts
144
+ import { StaticMap } from '@tinkatinka/static-map';
145
+ const map = new StaticMap({
146
+ width: 512,
147
+ height: 512,
148
+ extent: {
149
+ min: { lat: 52.4, lng: 13.3 },
150
+ max: { lat: 52.6, lng: 13.5 }
151
+ }
152
+ });
153
+ const src = await map.renderToDataURL();
154
+ ...
155
+ ```
156
+
157
+ ### with overlay image and computed extent
158
+ ```ts
159
+ import { StaticMap } from '@tinkatinka/static-map';
160
+ const map = new StaticMap({
161
+ width: 512,
162
+ height: 512,
163
+ paddingX: 32,
164
+ paddingY: 32,
165
+ tileCache: '/tmp/tiles'
166
+ })
167
+ .addImage('https://my.funky.src/image.png', {
168
+ min: { lat: 1.0, lng: 2.0 },
169
+ max: { lat: 2.0, lng: 3.0 }
170
+ });
171
+ const buffer = await map.renderToBuffer();
172
+ ...
173
+ ```
174
+
175
+ ### rendering to Canvas for custom drawing
176
+ ```ts
177
+ import { StaticMap } from '@tinkatinka/static-map'
178
+ const map = new StaticMap({
179
+ extent: {
180
+ min: { lat: 52.4, lng: 13.3 },
181
+ max: { lat: 52.6, lng: 13.5 }
182
+ },
183
+ grayscale: true,
184
+ tileCache: '/tmp/tiles'
185
+ });
186
+ const canvas = await map.renderToCanvas();
187
+ const ctx = canvas.getContext('2d');
188
+ ctx.textAlign = 'end';
189
+ ctx.textBaseline = 'bottom';
190
+ ctx.font = '16px sans-serif';
191
+ ctx.fillStyle = 'blue';
192
+ ctx.fillText('© OpenStreetMap contributors', canvas.width-8, canvas.height-8);
193
+ const buffer = await canvas.toBuffer();
194
+ ...
195
+ ```
196
+
197
+ ## Attribution
198
+ Depending on which tiles are being used, attribution of the data has to be provided. When using the static map image
199
+ you are responsible to do so.
200
+
201
+ E.g. see [OpenStreetMap](https://www.openstreetmap.org/copyright) for information regarding the copyright and
202
+ attribution of OpenStreetMap tiles.
@@ -0,0 +1,2 @@
1
+ declare const base64img: (url: string, mimetype?: string, userAgent?: string) => Promise<string>;
2
+ export default base64img;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const cross_fetch_1 = require("cross-fetch");
4
+ const base64img = async (url, mimetype = 'image/png', userAgent = 'StaticMap/1.0') => {
5
+ const response = await (0, cross_fetch_1.fetch)(url, {
6
+ headers: {
7
+ 'User-Agent': userAgent
8
+ }
9
+ });
10
+ if (response.status !== 200) {
11
+ throw new Error(`Server status ${response.status} for request '${url}'`);
12
+ }
13
+ const buf = await response.arrayBuffer();
14
+ const imgstr = Buffer.from(buf).toString('base64');
15
+ const dataurl = 'data:' + mimetype.trim() + ';base64,' + imgstr;
16
+ return dataurl;
17
+ };
18
+ exports.default = base64img;
@@ -0,0 +1,111 @@
1
+ /// <reference types="node" />
2
+ import Canvas from 'canvas';
3
+ declare type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;
4
+ export interface LatLng {
5
+ lat: number;
6
+ lng: number;
7
+ }
8
+ export interface LatLngBounds {
9
+ min: LatLng;
10
+ max: LatLng;
11
+ }
12
+ export interface StrokeOptions {
13
+ strokeStyle: string | CanvasGradient | CanvasPattern;
14
+ lineWidth: number;
15
+ lineJoin: 'bevel' | 'round' | 'miter';
16
+ lineCap: 'butt' | 'round' | 'square';
17
+ }
18
+ export interface FillOptions {
19
+ fillStyle: string | CanvasGradient | CanvasPattern;
20
+ }
21
+ export declare type StrokeFillOptions = Optional<StrokeOptions, 'strokeStyle'> & Optional<FillOptions, 'fillStyle'>;
22
+ export declare type StaticMapOverlay = StaticMapImage | StaticMapLine | StaticMapCircle | StaticMapText;
23
+ export interface StaticMapImage {
24
+ src: string;
25
+ bounds: LatLngBounds;
26
+ }
27
+ export interface StaticMapLine {
28
+ points: LatLng[];
29
+ options: StaticMapLineOptions;
30
+ }
31
+ export declare type StaticMapLineOptions = StrokeOptions;
32
+ export interface StaticMapCircle {
33
+ center: LatLng;
34
+ options: StaticMapCircleOptions;
35
+ }
36
+ export interface StaticMapCircleOptions extends StrokeFillOptions {
37
+ radius: number;
38
+ }
39
+ export interface StaticMapText {
40
+ text: string;
41
+ anchor: LatLng;
42
+ options: StaticMapTextOptions;
43
+ }
44
+ export interface StaticMapTextOptions extends CanvasTextDrawingStyles, StrokeFillOptions {
45
+ px: number;
46
+ py: number;
47
+ maxWidth?: number;
48
+ }
49
+ export interface StaticMapOptions {
50
+ width: number;
51
+ height: number;
52
+ padding: number;
53
+ paddingX?: number;
54
+ paddingY?: number;
55
+ paddingLeft?: number;
56
+ paddingRight?: number;
57
+ paddingTop?: number;
58
+ paddingBottom?: number;
59
+ extent?: LatLngBounds;
60
+ scaling: boolean;
61
+ tileURL: string;
62
+ tileSize: number;
63
+ tileMaxZoom: number;
64
+ tileCache?: string;
65
+ userAgent?: string;
66
+ backgroundColor?: string;
67
+ grayscale: boolean;
68
+ }
69
+ export declare class StaticMap {
70
+ private static defaultOptions;
71
+ private static defaultLineOptions;
72
+ private static defaultCircleOptions;
73
+ private static defaultTextOptions;
74
+ readonly options: StaticMapOptions;
75
+ get extent(): LatLngBounds | undefined;
76
+ get paddingLeft(): number;
77
+ get paddingRight(): number;
78
+ get paddingTop(): number;
79
+ get paddingBottom(): number;
80
+ private cache?;
81
+ private overlays;
82
+ constructor(options?: Partial<StaticMapOptions>);
83
+ renderToCanvas(): Promise<Canvas.Canvas>;
84
+ renderToDataURL(): Promise<string>;
85
+ renderToBuffer(): Promise<Buffer>;
86
+ addOverlay(overlay: StaticMapOverlay): StaticMap;
87
+ addImage(src: string, bounds: LatLngBounds): StaticMap;
88
+ addLines(points: LatLng[], options?: Partial<StaticMapLineOptions>): StaticMap;
89
+ addLine(src: LatLng, dst: LatLng, options?: Partial<StaticMapLineOptions>): StaticMap;
90
+ addCircle(center: LatLng, options?: Partial<StaticMapCircleOptions>): StaticMap;
91
+ addText(text: string, anchor: LatLng, options?: Partial<StaticMapTextOptions>): StaticMap;
92
+ private boundsCenter;
93
+ private lngToX;
94
+ private latToY;
95
+ private latlngToXY;
96
+ private xToPx;
97
+ private yToPy;
98
+ private xyToPxPy;
99
+ private lngToPx;
100
+ private latToPy;
101
+ private latlngToPxPy;
102
+ private xToLng;
103
+ private yToLat;
104
+ private overlayType;
105
+ private overlayExtent;
106
+ private calculateExtent;
107
+ private calculateZoom;
108
+ private loadTile;
109
+ private createCanvas;
110
+ }
111
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,407 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.StaticMap = void 0;
7
+ const canvas_1 = __importDefault(require("canvas"));
8
+ const lodash_merge_1 = __importDefault(require("lodash.merge"));
9
+ const tilecache_1 = require("./tilecache");
10
+ const base64img_1 = __importDefault(require("./base64img"));
11
+ class StaticMap {
12
+ constructor(options) {
13
+ this.options = (0, lodash_merge_1.default)({}, StaticMap.defaultOptions, options);
14
+ this.cache = this.options.tileCache ? new tilecache_1.TileCache(this.options.tileCache) : undefined;
15
+ this.overlays = [];
16
+ }
17
+ get extent() {
18
+ return this.options.extent ?? this.calculateExtent();
19
+ }
20
+ get paddingLeft() {
21
+ return this.options.paddingLeft ?? this.options.paddingX ?? this.options.padding;
22
+ }
23
+ get paddingRight() {
24
+ return this.options.paddingRight ?? this.options.paddingX ?? this.options.padding;
25
+ }
26
+ get paddingTop() {
27
+ return this.options.paddingTop ?? this.options.paddingY ?? this.options.padding;
28
+ }
29
+ get paddingBottom() {
30
+ return this.options.paddingBottom ?? this.options.paddingY ?? this.options.padding;
31
+ }
32
+ async renderToCanvas() {
33
+ return this.createCanvas();
34
+ }
35
+ async renderToDataURL() {
36
+ const canvas = await this.createCanvas();
37
+ return canvas.toDataURL('image/png');
38
+ }
39
+ async renderToBuffer() {
40
+ const canvas = await this.createCanvas();
41
+ return canvas.toBuffer('image/png');
42
+ }
43
+ addOverlay(overlay) {
44
+ this.overlays.push(overlay);
45
+ return this;
46
+ }
47
+ addImage(src, bounds) {
48
+ return this.addOverlay({ src, bounds });
49
+ }
50
+ addLines(points, options) {
51
+ if (points.length >= 2) {
52
+ return this.addOverlay({
53
+ points: points,
54
+ options: (0, lodash_merge_1.default)({}, StaticMap.defaultLineOptions, options)
55
+ });
56
+ }
57
+ return this;
58
+ }
59
+ addLine(src, dst, options) {
60
+ return this.addLines([src, dst], options);
61
+ }
62
+ addCircle(center, options) {
63
+ return this.addOverlay({
64
+ center: center,
65
+ options: (0, lodash_merge_1.default)({}, StaticMap.defaultCircleOptions, options)
66
+ });
67
+ }
68
+ addText(text, anchor, options) {
69
+ return this.addOverlay({
70
+ text: text,
71
+ anchor: anchor,
72
+ options: (0, lodash_merge_1.default)({}, StaticMap.defaultTextOptions, options)
73
+ });
74
+ }
75
+ boundsCenter(bounds) {
76
+ return {
77
+ lat: (bounds.max.lat + bounds.min.lat) / 2.0,
78
+ lng: (bounds.max.lng + bounds.min.lng) / 2.0
79
+ };
80
+ }
81
+ lngToX(lng, zoom) {
82
+ const l = (lng < -180 || lng > 180) ? (lng + 180) % 360 - 180 : lng;
83
+ return ((l + 180.0) / 360.0) * Math.pow(2, zoom);
84
+ }
85
+ latToY(lat, zoom) {
86
+ const l = (lat < -90 || lat > 90) ? (lat + 90) % 180 - 90 : lat;
87
+ const lr = l * Math.PI / 180.0;
88
+ return (1 - Math.log(Math.tan(lr) + 1 / Math.cos(lr)) / Math.PI) / 2 * Math.pow(2, zoom);
89
+ }
90
+ latlngToXY(geo, zoom) {
91
+ return {
92
+ x: this.lngToX(geo.lng, zoom),
93
+ y: this.latToY(geo.lat, zoom)
94
+ };
95
+ }
96
+ xToPx(x, centerX, scale = 1.0) {
97
+ return Math.round((x - centerX) * this.options.tileSize * scale
98
+ + (this.options.width + this.paddingLeft - this.paddingRight) / 2);
99
+ }
100
+ yToPy(y, centerY, scale = 1.0) {
101
+ return Math.round((y - centerY) * this.options.tileSize * scale
102
+ + (this.options.height + this.paddingTop - this.paddingBottom) / 2);
103
+ }
104
+ xyToPxPy(p, center, scale = 1.0) {
105
+ return {
106
+ x: this.xToPx(p.x, center.x, scale),
107
+ y: this.yToPy(p.y, center.y, scale)
108
+ };
109
+ }
110
+ lngToPx(lng, zoom, centerX, scale = 1.0) {
111
+ return this.xToPx(this.lngToX(lng, zoom), centerX, scale);
112
+ }
113
+ latToPy(lat, zoom, centerY, scale = 1.0) {
114
+ return this.yToPy(this.latToY(lat, zoom), centerY, scale);
115
+ }
116
+ latlngToPxPy(latlng, zoom, center, scale = 1.0) {
117
+ return {
118
+ x: this.lngToPx(latlng.lng, zoom, center.x, scale),
119
+ y: this.latToPy(latlng.lat, zoom, center.y, scale)
120
+ };
121
+ }
122
+ xToLng(x, zoom) {
123
+ return x / Math.pow(2, zoom) * 360.0 - 180.0;
124
+ }
125
+ yToLat(y, zoom) {
126
+ return Math.atan(Math.sinh(Math.PI * (1 - 2 * y / Math.pow(2, zoom)))) / Math.PI * 180.0;
127
+ }
128
+ overlayType(overlay) {
129
+ if (overlay.bounds !== undefined) {
130
+ return 'image';
131
+ }
132
+ else if (overlay.center !== undefined) {
133
+ return 'circle';
134
+ }
135
+ else if (overlay.anchor !== undefined) {
136
+ return 'text';
137
+ }
138
+ else {
139
+ return 'line';
140
+ }
141
+ }
142
+ overlayExtent(overlay) {
143
+ const type = this.overlayType(overlay);
144
+ switch (type) {
145
+ case 'image':
146
+ return overlay.bounds;
147
+ case 'circle': {
148
+ const c = overlay.center;
149
+ return { min: c, max: c };
150
+ }
151
+ case 'line': {
152
+ const min = (arr) => arr.reduce((prev, curr) => ((curr < prev) ? curr : prev));
153
+ const max = (arr) => arr.reduce((prev, curr) => ((curr > prev) ? curr : prev));
154
+ const bounds = (points) => ({
155
+ min: {
156
+ lat: min(points.map(p => p.lat)),
157
+ lng: min(points.map(p => p.lng))
158
+ },
159
+ max: {
160
+ lat: max(points.map(p => p.lat)),
161
+ lng: max(points.map(p => p.lng))
162
+ }
163
+ });
164
+ return bounds(overlay.points);
165
+ }
166
+ case 'text': {
167
+ const a = overlay.anchor;
168
+ return { min: a, max: a };
169
+ }
170
+ default:
171
+ throw new Error(`Unknown overlay type "${type}"`);
172
+ }
173
+ }
174
+ calculateExtent() {
175
+ if (this.overlays.length < 1) {
176
+ return undefined;
177
+ }
178
+ if (this.overlays.length < 2) {
179
+ return this.overlayExtent(this.overlays[0]);
180
+ }
181
+ const min = (arr) => arr.reduce((prev, curr) => ((curr < prev) ? curr : prev));
182
+ const max = (arr) => arr.reduce((prev, curr) => ((curr > prev) ? curr : prev));
183
+ const union = (arr) => ({
184
+ min: {
185
+ lat: min(arr.map(b => b.min.lat)),
186
+ lng: min(arr.map(b => b.min.lng))
187
+ },
188
+ max: {
189
+ lat: max(arr.map(b => b.max.lat)),
190
+ lng: max(arr.map(b => b.max.lng))
191
+ }
192
+ });
193
+ return union(this.overlays.map(this.overlayExtent.bind(this)));
194
+ }
195
+ calculateZoom(extent) {
196
+ let z = this.options.tileMaxZoom + 1;
197
+ while (z > 0) {
198
+ z--;
199
+ const w = (this.lngToX(extent.max.lng, z) - this.lngToX(extent.min.lng, z)) * this.options.tileSize;
200
+ if (w > (this.options.width - (this.paddingLeft + this.paddingRight))) {
201
+ continue;
202
+ }
203
+ const h = (this.latToY(extent.min.lat, z) - this.latToY(extent.max.lat, z)) * this.options.tileSize;
204
+ if (h > (this.options.height - (this.paddingTop + this.paddingBottom))) {
205
+ continue;
206
+ }
207
+ return z;
208
+ }
209
+ return 0;
210
+ }
211
+ async loadTile(zoom, tileX, tileY) {
212
+ const url = this.options.tileURL
213
+ .replace('{z}', zoom.toString())
214
+ .replace('{x}', tileX.toString())
215
+ .replace('{y}', tileY.toString());
216
+ let src = url;
217
+ if (this.cache !== undefined) {
218
+ const td = { z: zoom, x: tileX, y: tileY };
219
+ try {
220
+ const csrc = await this.cache.pass(td, () => (0, base64img_1.default)(src, 'image/png', this.options.userAgent));
221
+ if (csrc !== undefined) {
222
+ src = csrc;
223
+ }
224
+ }
225
+ catch (error) {
226
+ console.error(error);
227
+ throw error;
228
+ }
229
+ }
230
+ else {
231
+ src = await (0, base64img_1.default)(src, 'image/png', this.options.userAgent);
232
+ }
233
+ const image = await canvas_1.default.loadImage(src);
234
+ return image;
235
+ }
236
+ async createCanvas() {
237
+ const extent = this.extent;
238
+ if (extent === undefined) {
239
+ throw new Error('Undefined extent');
240
+ }
241
+ const { width, height, scaling, backgroundColor, grayscale, tileSize } = this.options;
242
+ const canvas = canvas_1.default.createCanvas(width, height);
243
+ const ctx = canvas.getContext('2d');
244
+ if (backgroundColor !== undefined) {
245
+ ctx.fillStyle = backgroundColor;
246
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
247
+ }
248
+ const zoom = this.calculateZoom(extent);
249
+ const center = this.boundsCenter(extent);
250
+ const centerXY = this.latlngToXY(center, zoom);
251
+ let scale;
252
+ if (scaling) {
253
+ const scaleX = (width - (this.paddingLeft + this.paddingRight)) / Math.abs(this.lngToPx(extent.max.lng, zoom, centerXY.x) - this.lngToPx(extent.min.lng, zoom, centerXY.x));
254
+ const scaleY = (height - (this.paddingTop + this.paddingBottom)) / Math.abs(this.latToPy(extent.min.lat, zoom, centerXY.y) - this.latToPy(extent.max.lat, zoom, centerXY.y));
255
+ scale = Math.min(scaleX, scaleY);
256
+ }
257
+ const minX = Math.floor(centerXY.x - 0.5 * width / tileSize);
258
+ const maxX = Math.ceil(centerXY.x + 0.5 * width / tileSize);
259
+ const minY = Math.floor(centerXY.y - 0.5 * height / tileSize);
260
+ const maxY = Math.ceil(centerXY.y + 0.5 * height / tileSize);
261
+ const maxTile = Math.pow(2, zoom);
262
+ for (let x = minX; x < maxX; x++) {
263
+ for (let y = minY; y < maxY; y++) {
264
+ const tileX = (x + maxTile) % maxTile;
265
+ const tileY = (y + maxTile) % maxTile;
266
+ const image = await this.loadTile(zoom, tileX, tileY);
267
+ const p = this.xyToPxPy({ x, y }, centerXY, scale);
268
+ const dx = this.xToPx(x + 1, centerXY.x, scale) - p.x;
269
+ const dy = this.yToPy(y + 1, centerXY.y, scale) - p.y;
270
+ ctx.drawImage(image, p.x, p.y, dx, dy);
271
+ }
272
+ }
273
+ if (grayscale) {
274
+ const imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
275
+ const pixels = imgData.data;
276
+ for (let i = 0; i < pixels.length; i += 4) {
277
+ const lightness = (pixels[i] + pixels[i + 1] + pixels[i + 2]) / 3;
278
+ pixels[i] = lightness;
279
+ pixels[i + 1] = lightness;
280
+ pixels[i + 2] = lightness;
281
+ }
282
+ ctx.putImageData(imgData, 0, 0);
283
+ }
284
+ for (const overlay of this.overlays) {
285
+ const type = this.overlayType(overlay);
286
+ switch (type) {
287
+ case 'image': {
288
+ const imgdata = overlay;
289
+ let img;
290
+ try {
291
+ img = new canvas_1.default.Image();
292
+ }
293
+ catch {
294
+ img = new Image();
295
+ img.crossOrigin = 'anonymous';
296
+ }
297
+ const draw = async () => new Promise((resolve, reject) => {
298
+ img.onload = () => {
299
+ const x = this.lngToPx(imgdata.bounds.min.lng, zoom, centerXY.x, scale);
300
+ const y = this.latToPy(imgdata.bounds.max.lat, zoom, centerXY.y, scale);
301
+ const dx = this.lngToPx(imgdata.bounds.max.lng, zoom, centerXY.x, scale) - x;
302
+ const dy = this.latToPy(imgdata.bounds.min.lat, zoom, centerXY.y, scale) - y;
303
+ ctx.drawImage(img, x, y, dx, dy);
304
+ resolve();
305
+ };
306
+ img.onerror = reject;
307
+ img.src = imgdata.src;
308
+ });
309
+ await draw();
310
+ break;
311
+ }
312
+ case 'line': {
313
+ const linedata = overlay;
314
+ if (linedata.points.length > 1) {
315
+ const p0 = this.latlngToPxPy(linedata.points[0], zoom, centerXY, scale);
316
+ ctx.beginPath();
317
+ ctx.moveTo(p0.x, p0.y);
318
+ for (const p of linedata.points.slice(1)) {
319
+ const pxy = this.latlngToPxPy(p, zoom, centerXY, scale);
320
+ ctx.lineTo(pxy.x, pxy.y);
321
+ }
322
+ ctx.strokeStyle = linedata.options.strokeStyle;
323
+ ctx.lineWidth = linedata.options.lineWidth;
324
+ ctx.lineCap = linedata.options.lineCap;
325
+ ctx.lineJoin = linedata.options.lineJoin;
326
+ ctx.stroke();
327
+ }
328
+ break;
329
+ }
330
+ case 'circle': {
331
+ const circdata = overlay;
332
+ const ccenter = this.latlngToPxPy(circdata.center, zoom, centerXY, scale);
333
+ ctx.beginPath();
334
+ ctx.arc(ccenter.x, ccenter.y, circdata.options.radius, 0, 2 * Math.PI, false);
335
+ if (circdata.options.fillStyle) {
336
+ ctx.fillStyle = circdata.options.fillStyle;
337
+ ctx.fill();
338
+ }
339
+ if (circdata.options.strokeStyle && circdata.options.lineWidth > 0) {
340
+ ctx.strokeStyle = circdata.options.strokeStyle;
341
+ ctx.lineWidth = circdata.options.lineWidth;
342
+ ctx.stroke();
343
+ }
344
+ break;
345
+ }
346
+ case 'text': {
347
+ const textdata = overlay;
348
+ const anchor = this.latlngToPxPy(textdata.anchor, zoom, centerXY, scale);
349
+ const opts = textdata.options;
350
+ ctx.textAlign = opts.textAlign;
351
+ ctx.textBaseline = opts.textBaseline;
352
+ ctx.direction = opts.direction;
353
+ ctx.font = opts.font;
354
+ if (opts.fillStyle) {
355
+ ctx.fillStyle = opts.fillStyle;
356
+ ctx.fillText(textdata.text, anchor.x + opts.px, anchor.y + opts.py, opts.maxWidth);
357
+ }
358
+ if (opts.strokeStyle) {
359
+ ctx.strokeStyle = opts.strokeStyle;
360
+ ctx.strokeText(textdata.text, anchor.x + opts.px, anchor.y + opts.py, opts.maxWidth);
361
+ }
362
+ break;
363
+ }
364
+ default:
365
+ throw new Error(`Unknown overlay type "${type}"`);
366
+ }
367
+ }
368
+ return canvas;
369
+ }
370
+ }
371
+ exports.StaticMap = StaticMap;
372
+ StaticMap.defaultOptions = {
373
+ width: 512,
374
+ height: 512,
375
+ padding: 0,
376
+ scaling: true,
377
+ tileURL: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
378
+ tileSize: 256,
379
+ tileMaxZoom: 20,
380
+ grayscale: false
381
+ };
382
+ StaticMap.defaultLineOptions = {
383
+ strokeStyle: 'black',
384
+ lineWidth: 1.0,
385
+ lineCap: 'round',
386
+ lineJoin: 'round'
387
+ };
388
+ StaticMap.defaultCircleOptions = {
389
+ radius: 5.0,
390
+ strokeStyle: 'rgba(0.5, 0.5, 0.5, 0.5)',
391
+ lineWidth: 1.0,
392
+ lineCap: 'round',
393
+ lineJoin: 'round',
394
+ fillStyle: 'rgba(0, 0, 0, 0.5)'
395
+ };
396
+ StaticMap.defaultTextOptions = {
397
+ px: 0,
398
+ py: 0,
399
+ textAlign: 'center',
400
+ textBaseline: 'middle',
401
+ direction: 'inherit',
402
+ font: '12px sans-serif',
403
+ lineWidth: 1.0,
404
+ lineCap: 'round',
405
+ lineJoin: 'round',
406
+ fillStyle: 'black'
407
+ };
@@ -0,0 +1,14 @@
1
+ export interface TileData {
2
+ z: number;
3
+ x: number;
4
+ y: number;
5
+ }
6
+ export declare class TileCache {
7
+ static fnTemplate: string;
8
+ path: string;
9
+ constructor(path: string);
10
+ pass(data: TileData, generator: (data: TileData) => Promise<string>): Promise<string>;
11
+ read(data: TileData): Promise<string | undefined>;
12
+ write(data: TileData, src: string): Promise<void>;
13
+ private tilePath;
14
+ }
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TileCache = void 0;
4
+ const fs_1 = require("fs");
5
+ const path_1 = require("path");
6
+ const util_1 = require("util");
7
+ class TileCache {
8
+ constructor(path) {
9
+ this.path = path;
10
+ (0, fs_1.mkdirSync)(path, { recursive: true });
11
+ }
12
+ async pass(data, generator) {
13
+ let buf = await this.read(data);
14
+ if (buf === undefined) {
15
+ buf = await generator(data);
16
+ await this.write(data, buf);
17
+ }
18
+ return buf;
19
+ }
20
+ async read(data) {
21
+ const p = this.tilePath(data);
22
+ const r = (0, fs_1.existsSync)(p) ? await (0, util_1.promisify)(fs_1.readFile)(p, { encoding: 'utf-8' }) : undefined;
23
+ return r;
24
+ }
25
+ async write(data, src) {
26
+ const p = this.tilePath(data);
27
+ await (0, util_1.promisify)(fs_1.writeFile)(p, src, { encoding: 'utf-8' });
28
+ }
29
+ tilePath(data) {
30
+ const fn = TileCache.fnTemplate
31
+ .replace('{z}', data.z.toString())
32
+ .replace('{x}', data.x.toString())
33
+ .replace('{y}', data.y.toString());
34
+ return (0, path_1.join)(this.path, fn);
35
+ }
36
+ }
37
+ exports.TileCache = TileCache;
38
+ TileCache.fnTemplate = '{z}_{x}_{y}.png';
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@tinkatinka/static-map",
3
+ "version": "1.4.4",
4
+ "description": "Render static map images",
5
+ "author": "Florian Gmeiner <florian@tinkatinka.com>",
6
+ "license": "MIT",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/tinkatinka/static-map.git"
15
+ },
16
+ "bugs": {
17
+ "url": "https://github.com/tinkatinka/static-map/issues"
18
+ },
19
+ "homepage": "https://github.com/tinkatinka/static-map#readme",
20
+ "keywords": [
21
+ "map",
22
+ "tiles",
23
+ "static"
24
+ ],
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.build.json",
27
+ "clean": "rm -rf dist/*",
28
+ "lint": "eslint . --ext .ts,.tsx,.js,.jsx",
29
+ "test": "jest"
30
+ },
31
+ "browser": {
32
+ "node-fetch": false
33
+ },
34
+ "devDependencies": {
35
+ "@types/jest": "^27.0.1",
36
+ "@types/jest-image-snapshot": "^4.3.0",
37
+ "@types/lodash.merge": "^4.6.6",
38
+ "@types/node": "^16.0.0",
39
+ "@typescript-eslint/eslint-plugin": "^4.28.1",
40
+ "canvas": "^2.8.0",
41
+ "cross-fetch": "^3.1.4",
42
+ "eslint-plugin-import": "^2.23.4",
43
+ "jest": "^27.0.6",
44
+ "jest-image-snapshot": "^4.5.1",
45
+ "lodash.merge": "^4.6.2",
46
+ "ts-jest": "^27.0.3",
47
+ "typescript": "^4.3.4"
48
+ },
49
+ "peerDependencies": {
50
+ "canvas": "^2.8.0",
51
+ "cross-fetch": "^3.1.4",
52
+ "lodash.merge": "^4.6.2"
53
+ }
54
+ }