Skip to content

Commit 5cb16e0

Browse files
committed
Improve speed, upgrade deps, and minor fixes
1 parent 67189a0 commit 5cb16e0

File tree

10 files changed

+103
-54
lines changed

10 files changed

+103
-54
lines changed

.buildpacks

Lines changed: 0 additions & 2 deletions
This file was deleted.

CHANGELOG.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
1+
# 3.11.0
2+
3+
Improve speed
4+
5+
- Speed up results:
6+
- Add cache to resolve faster tilesets in sample-server
7+
- Correct default tile url to use https to avoid redirection
8+
- Remove unnecessary network wait. Change it to wait for map load event
9+
- Remove tile fade-in effect to be able to resolve earlier
10+
- Upgrade all dependencies to latest versions
11+
- Removed not-working heroku demo
12+
- Removed validation that broke the /dynamic endpoint
13+
114
# 3.10.3
215

316
Support AWS functions hotfix

Dockerfile

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
FROM node:14.2
1+
FROM node:22.0
22

33
RUN \
44
apt-get update \
@@ -11,6 +11,8 @@ RUN \
1111
libasound2 \
1212
libatk-bridge2.0-0 \
1313
libgtk-3-0 \
14+
libdrm2 \
15+
libgbm1 \
1416
fonts-wqy-zenhei \
1517
&& \
1618
rm -rf /var/lib/apt/lists/*

Procfile

Lines changed: 0 additions & 1 deletion
This file was deleted.

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
Openstreetmap static maps is a nodejs lib, CLI and server open source inspired on google static map service
44

5-
Here you have a [demo](http://osm-static-maps.herokuapp.com/?geojson=[{"type":"Feature","properties":{"party":"Republican"},"geometry":{"type":"Polygon","coordinates":[[[-104.05,48.99],[-97.22,48.98],[-96.58,45.94],[-104.03,45.94],[-104.05,48.99]]]}},{"type":"Feature","properties":{"party":"Democrat"},"geometry":{"type":"Polygon","coordinates":[[[-109.05,41.00],[-102.06,40.99],[-102.03,36.99],[-109.04,36.99],[-109.05,41.00]]]}}]&height=300&width=300 "Just what I wanted!"). Also a [dynamic version](http://osm-static-maps.herokuapp.com/dynamic?geojson=[{"type":"Feature","properties":{"party":"Republican"},"geometry":{"type":"Polygon","coordinates":[[[-104.05,48.99],[-97.22,48.98],[-96.58,45.94],[-104.03,45.94],[-104.05,48.99]]]}},{"type":"Feature","properties":{"party":"Democrat"},"geometry":{"type":"Polygon","coordinates":[[[-109.05,41.00],[-102.06,40.99],[-102.03,36.99],[-109.04,36.99],[-109.05,41.00]]]}}]&height=300&width=300 "Wow it gets even better!!") of the demo, for testing purposes.
5+
Here you have a [demo](http://localhost:3000/?geojson=[{"type":"Feature","properties":{"party":"Republican"},"geometry":{"type":"Polygon","coordinates":[[[-104.05,48.99],[-97.22,48.98],[-96.58,45.94],[-104.03,45.94],[-104.05,48.99]]]}},{"type":"Feature","properties":{"party":"Democrat"},"geometry":{"type":"Polygon","coordinates":[[[-109.05,41.00],[-102.06,40.99],[-102.03,36.99],[-109.04,36.99],[-109.05,41.00]]]}}]&height=300&width=300 "Just what I wanted!"). Also a [dynamic version](http://localhost:3000/dynamic?geojson=[{"type":"Feature","properties":{"party":"Republican"},"geometry":{"type":"Polygon","coordinates":[[[-104.05,48.99],[-97.22,48.98],[-96.58,45.94],[-104.03,45.94],[-104.05,48.99]]]}},{"type":"Feature","properties":{"party":"Democrat"},"geometry":{"type":"Polygon","coordinates":[[[-109.05,41.00],[-102.06,40.99],[-102.03,36.99],[-109.04,36.99],[-109.05,41.00]]]}}]&height=300&width=300 "Wow it gets even better!!") of the demo, for testing purposes.
66

77
## How to use
88

package.json

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "osm-static-maps",
3-
"version": "3.10.3",
3+
"version": "3.11.0",
44
"description": "Create a static image of a map with the features you want",
55
"author": "Julian Perelli",
66
"contributors": [
@@ -15,18 +15,18 @@
1515
"url": "http://github.com/jperelli/osm-static-maps.git"
1616
},
1717
"dependencies": {
18-
"chrome-aws-lambda": "^5.5.0",
19-
"commander": "^6.2.1",
20-
"express": "4.17.1",
21-
"handlebars": "4.7.6",
22-
"imagemin": "7.0.1",
18+
"chrome-aws-lambda": "^10.1.0",
19+
"commander": "^12.0.0",
20+
"express": "^4.19.2",
21+
"handlebars": "^4.7.8",
22+
"imagemin": "^8.0.1",
2323
"imagemin-jpegtran": "7.0.0",
2424
"imagemin-optipng": "8.0.0",
25-
"leaflet": "^1.7.1",
25+
"leaflet": "^1.9.4",
2626
"leaflet-polylinedecorator": "1.6.0",
2727
"mapbox-gl": "^1.13.0",
2828
"mapbox-gl-leaflet": "0.0.14",
29-
"puppeteer-core": "^5.5.0"
29+
"puppeteer-core": "^22.7.1"
3030
},
3131
"engines": {
3232
"node": ">=12"
@@ -41,7 +41,10 @@
4141
"osmsm": "./src/cli.js"
4242
},
4343
"devDependencies": {
44-
"nodemon": "2.0.6",
45-
"puppeteer": "^5.5.0"
44+
"nodemon": "^3.1.0",
45+
"puppeteer": "^22.7.1"
46+
},
47+
"overrides": {
48+
"puppeteer-core": "^22.7.1"
4649
}
47-
}
50+
}

src/cli.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env node
22

3-
const program = require("commander");
3+
const { program } = require("commander");
44
const osmsm = require("./lib");
55
const package = require("../package.json");
66

src/lib.js

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -44,10 +44,11 @@ class Browser {
4444
this.browser = null;
4545
}
4646
async launch() {
47+
const executablePath = await chrome.executablePath
4748
return puppeteer.launch({
4849
args: [...chrome.args, "--no-sandbox", "--disable-setuid-sandbox"],
4950
defaultViewport: chrome.defaultViewport,
50-
executablePath: await chrome.executablePath,
51+
executablePath,
5152
headless: true,
5253
ignoreHTTPSErrors: true,
5354
});
@@ -57,7 +58,6 @@ class Browser {
5758
throw new Error('osm-static-maps is not ready, please wait a few seconds')
5859
}
5960
if (!this.browser || !this.browser.isConnected()) {
60-
// console.log('NEW BROWSER')
6161
this.openingBrowser = true;
6262
try {
6363
this.browser = await this.launch();
@@ -72,7 +72,6 @@ class Browser {
7272
}
7373
async getPage() {
7474
const browser = await this.getBrowser()
75-
// console.log("NEW PAGE");
7675
return browser.newPage()
7776
}
7877
}
@@ -100,8 +99,51 @@ function httpGet(url) {
10099

101100
process.on("warning", (e) => console.warn(e.stack));
102101

102+
103+
// add network cache to cache tiles
104+
const cache = {};
105+
async function configCache(page) {
106+
await page.setRequestInterception(true);
107+
108+
page.on('request', async (request) => {
109+
const url = request.url();
110+
if (cache[url] && cache[url].expires > Date.now()) {
111+
await request.respond(cache[url]);
112+
return;
113+
}
114+
request.continue();
115+
});
116+
117+
page.on('response', async (response) => {
118+
const url = response.url();
119+
const headers = response.headers();
120+
const cacheControl = headers['cache-control'] || '';
121+
const maxAgeMatch = cacheControl.match(/max-age=(\d+)/);
122+
const maxAge = maxAgeMatch && maxAgeMatch.length > 1 ? parseInt(maxAgeMatch[1], 10) : 0;
123+
if (maxAge) {
124+
if (cache[url] && cache[url].expires > Date.now()) return;
125+
126+
let buffer;
127+
try {
128+
buffer = await response.buffer();
129+
} catch (error) {
130+
// some responses do not contain buffer and do not need to be catched
131+
return;
132+
}
133+
134+
cache[url] = {
135+
status: response.status(),
136+
headers: response.headers(),
137+
body: buffer,
138+
expires: Date.now() + (maxAge * 1000),
139+
};
140+
}
141+
});
142+
}
143+
103144
module.exports = function(options) {
104145
return new Promise(function(resolve, reject) {
146+
// TODO: validate options to avoid template injection
105147
options = options || {};
106148
options.geojson = (options.geojson && (typeof options.geojson === 'string' ? options.geojson : JSON.stringify(options.geojson))) || '';
107149
options.geojsonfile = options.geojsonfile || '';
@@ -111,7 +153,7 @@ module.exports = function(options) {
111153
options.zoom = options.zoom || '';
112154
options.maxZoom = options.maxZoom || (options.vectorserverUrl ? 20 : 17);
113155
options.attribution = options.attribution || 'osm-static-maps | © OpenStreetMap contributors';
114-
options.tileserverUrl = options.tileserverUrl || 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
156+
options.tileserverUrl = options.tileserverUrl || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
115157
options.vectorserverUrl = options.vectorserverUrl || '';
116158
options.vectorserverToken = options.vectorserverToken || 'no-token';
117159
options.imagemin = options.imagemin || false;
@@ -149,19 +191,24 @@ module.exports = function(options) {
149191
}
150192

151193
const page = await browser.getPage();
194+
await configCache(page);
152195
try {
153196
page.on('error', function (err) { reject(err.toString()) })
154197
page.on('pageerror', function (err) { reject(err.toString()) })
155-
page.on('console', function (msg) {
156-
if (options.haltOnConsoleError && msg.type() === "error") {
157-
reject(JSON.stringify(msg));
158-
}
159-
})
198+
if (options.haltOnConsoleError) {
199+
page.on('console', function (msg) {
200+
if (msg.type() === "error") {
201+
reject(JSON.stringify(msg));
202+
}
203+
})
204+
}
160205
await page.setViewport({
161206
width: Number(options.width),
162207
height: Number(options.height)
163208
});
164-
await page.setContent(html, { waitUntil: 'networkidle0', timeout: Number(options.timeout) });
209+
210+
await page.setContent(html);
211+
await page.waitForFunction(() => window.mapRendered === true, { timeout: Number(options.timeout) });
165212

166213
let imageBinary = await page.screenshot({
167214
type: options.type || 'png',
@@ -205,11 +252,10 @@ module.exports = function(options) {
205252
}
206253
catch(e) {
207254
page.close();
208-
// console.log("PAGE CLOSED with err" + e);
255+
console.log("PAGE CLOSED with err" + e);
209256
throw(e);
210257
}
211258
page.close();
212-
// console.log("PAGE CLOSED ok");
213259

214260
})().catch(reject)
215261
});

src/server.js

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -33,22 +33,6 @@ app.use((req, res, next) => {
3333
next();
3434
});
3535

36-
37-
function htmlEscape(text) {
38-
return text.replace(/&/g, '&').
39-
replace(/</g, '&lt;').
40-
replace(/"/g, '&quot;').
41-
replace(/'/g, '&#039;');
42-
}
43-
44-
function sanitize(params) {
45-
let result = {}
46-
for (let [key, value] of Object.entries(params)) {
47-
result[key] = htmlEscape(value)
48-
}
49-
return result;
50-
}
51-
5236
app.get("/health", (req, res) => res.sendStatus(200));
5337

5438
const handler = (res, params) => {
@@ -71,13 +55,11 @@ app.get("/", (req, res) => handler(res, req.query));
7155
app.post("/", (req, res) => handler(res, req.body));
7256

7357
app.get("/dynamic", (req, res) => {
74-
var sanitized = sanitize(req.query)
75-
handler(res, { ...sanitized, renderToHtml: true })
58+
handler(res, { ...req.query, renderToHtml: true })
7659
})
7760

7861
app.post("/dynamic", (req, res) => {
79-
var sanitized = sanitize(req.body)
80-
handler(res, { ...sanitized, renderToHtml: true })
62+
handler(res, { ...req.body, renderToHtml: true })
8163
})
8264

8365
module.exports = http.createServer(app);

src/template.html

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33
<head>
44
<style>
55
//leafletcss//
6+
.leaflet-tile {
7+
opacity: 1 !important;
8+
}
69
.leaflet-fade-anim, .leaflet-zoom-anim {
710
transition: none;
811
}
@@ -132,24 +135,27 @@
132135
{{/if}}
133136

134137
{{#if vectorserverUrl}}
135-
L.mapboxGL({
138+
var backgroundLayer = L.mapboxGL({
136139
accessToken: '{{ vectorserverToken }}',
137140
style: '{{{ vectorserverUrl }}}'
138-
}).addTo(map);
141+
});
139142
{{else}}
140143
{{#if tileserverUrl}}
141-
L.tileLayer(
144+
var backgroundLayer = L.tileLayer(
142145
'{{{tileserverUrl}}}',
143146
{
144147
maxZoom: maxZoom,
145148
fadeAnimation: false
146149
}
147-
).addTo(map);
150+
);
148151
{{/if}}
149152
{{/if}}
153+
backgroundLayer.addTo(map);
154+
backgroundLayer.on('load', function() {
155+
window.mapRendered = true;
156+
});
150157

151158

152159
</script>
153160
</body>
154161
</html>
155-

0 commit comments

Comments
 (0)