├── .github ├── FUNDING.yml └── workflows │ └── npm-publish.yml ├── .dockerignore ├── .gitignore ├── docker-compose.yml ├── Dockerfile ├── Dockerfile.prod ├── package.json ├── src ├── server.js ├── lib.d.ts ├── cli.js ├── template.html └── lib.js ├── CHANGELOG.md ├── README.md └── LICENSE /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: jperelli 2 | -------------------------------------------------------------------------------- /.dockerignore: -------------------------------------------------------------------------------- 1 | .github 2 | node_modules 3 | .dockerignore 4 | .gitignore 5 | *.md 6 | docker* 7 | Docker* 8 | LICENSE 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | 10 | pids 11 | logs 12 | results 13 | 14 | npm-debug.log 15 | node_modules 16 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.2" 2 | 3 | services: 4 | 5 | osmsm: 6 | build: . 7 | ports: 8 | - 3000:3000 9 | volumes: 10 | - .:/app 11 | restart: unless-stopped 12 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:22.0 2 | 3 | RUN \ 4 | apt-get update \ 5 | && \ 6 | apt-get install -y \ 7 | libx11-xcb1 \ 8 | libxtst6 \ 9 | libnss3 \ 10 | libxss1 \ 11 | libasound2 \ 12 | libatk-bridge2.0-0 \ 13 | libgtk-3-0 \ 14 | libdrm2 \ 15 | libgbm1 \ 16 | fonts-wqy-zenhei \ 17 | && \ 18 | rm -rf /var/lib/apt/lists/* 19 | 20 | RUN \ 21 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ 22 | && \ 23 | /root/.cargo/bin/cargo install oxipng 24 | 25 | WORKDIR /app 26 | EXPOSE 3000 27 | CMD [ "npm", "run", "installandstartdev" ] 28 | 29 | HEALTHCHECK CMD curl -f http://localhost:3000/health || exit 1 30 | -------------------------------------------------------------------------------- /Dockerfile.prod: -------------------------------------------------------------------------------- 1 | FROM node:22.0 2 | 3 | RUN \ 4 | apt-get update \ 5 | && \ 6 | apt-get install -y \ 7 | libx11-xcb1 \ 8 | libxtst6 \ 9 | libnss3 \ 10 | libxss1 \ 11 | libasound2 \ 12 | libatk-bridge2.0-0 \ 13 | libgtk-3-0 \ 14 | libdrm2 \ 15 | libgbm1 \ 16 | fonts-wqy-zenhei \ 17 | && \ 18 | rm -rf /var/lib/apt/lists/* 19 | 20 | RUN \ 21 | curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ 22 | && \ 23 | /root/.cargo/bin/cargo install oxipng 24 | 25 | EXPOSE 3000 26 | 27 | WORKDIR /app 28 | 29 | COPY . /app 30 | 31 | RUN npm install && (cd node_modules/optipng-bin && npm run postinstall) 32 | 33 | CMD [ "npm", "run", "start" ] 34 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | publish-npm: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions/setup-node@v1 16 | with: 17 | node-version: 12 18 | registry-url: https://registry.npmjs.org/ 19 | - run: npm i 20 | - run: npm publish 21 | env: 22 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 23 | 24 | publish-gpr: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v2 28 | - uses: actions/setup-node@v1 29 | with: 30 | node-version: 12 31 | registry-url: https://npm.pkg.github.com/ 32 | - run: npm i 33 | - run: npm publish 34 | env: 35 | NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "osm-static-maps", 3 | "version": "4.0.2", 4 | "description": "Create a static image of a map with the features you want", 5 | "author": "Julian Perelli", 6 | "contributors": [ 7 | { 8 | "name": "Julian Perelli", 9 | "email": "jperelli@gmail.com" 10 | } 11 | ], 12 | "license": "GPLv2", 13 | "repository": { 14 | "type": "git", 15 | "url": "http://github.com/jperelli/osm-static-maps.git" 16 | }, 17 | "dependencies": { 18 | "chrome-aws-lambda": "^10.1.0", 19 | "commander": "^12.1.0", 20 | "express": "^4.19.2", 21 | "handlebars": "^4.7.8", 22 | "imagemin": "^9.0.0", 23 | "imagemin-jpegtran": "7.0.0", 24 | "imagemin-optipng": "8.0.0", 25 | "leaflet": "^1.9.4", 26 | "leaflet-polylinedecorator": "1.6.0", 27 | "mapbox-gl": "^1.13.0", 28 | "mapbox-gl-leaflet": "0.0.14", 29 | "puppeteer-core": "^23.2.0" 30 | }, 31 | "engines": { 32 | "node": ">=12" 33 | }, 34 | "scripts": { 35 | "start": "node src/cli.js serve", 36 | "dev": "nodemon -e js,html src/cli.js serve", 37 | "installandstartdev": "npm install --loglevel=verbose --foreground-scripts && (cd node_modules/optipng-bin && npm run postinstall) && npm run dev" 38 | }, 39 | "main": "./src/lib.js", 40 | "type": "module", 41 | "bin": { 42 | "osmsm": "./src/cli.js" 43 | }, 44 | "devDependencies": { 45 | "nodemon": "^3.1.4", 46 | "puppeteer": "^23.2.0" 47 | }, 48 | "overrides": { 49 | "puppeteer-core": "^23.2.0" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/server.js: -------------------------------------------------------------------------------- 1 | import express, { json } from "express"; 2 | import { createServer } from "http"; 3 | import osmsm from "./lib.js"; 4 | import { fileURLToPath } from 'url'; 5 | import path from 'path'; 6 | 7 | const __filename = fileURLToPath(import.meta.url); 8 | const __dirname = path.dirname(__filename); 9 | 10 | const app = express(); 11 | // app.set("port", process.env.PORT || 3000); 12 | app.set("views", __dirname + "/lib"); 13 | app.set("view engine", "handlebars"); 14 | app.set("view options", { layout: false }); 15 | app.use(json({ limit: "50mb" })); 16 | 17 | app.use((req, res, next) => { 18 | const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress; 19 | const date = new Date().toISOString(); 20 | const ref = req.header("Referer"); 21 | const ua = req.header("user-agent"); 22 | const url = req.originalUrl; 23 | const logLine = `[${date} - ${ip}] (${ref}) {${ua}} ${url}`; 24 | if (process.env.HEADER_CHECK) { 25 | const header = process.env.HEADER_CHECK.split(":"); 26 | if (req.headers[header[0]] !== header[1]) { 27 | res 28 | .status(403) 29 | .send( 30 | process.env.HEADER_CHECK_FAIL_MESSAGE || 31 | "Forbidden, set correct header to access" 32 | ); 33 | console.log(`${logLine} FORBIDDEN, HEADER_CHECK FAILED`); 34 | return; 35 | } 36 | } 37 | console.log(logLine); 38 | next(); 39 | }); 40 | 41 | app.get("/health", (req, res) => res.sendStatus(200)); 42 | 43 | const handler = (res, params) => { 44 | const filename = params.f || params.geojsonfile 45 | if ( 46 | filename && 47 | !(filename.startsWith("http://") || 48 | filename.startsWith("https://")) 49 | ) { 50 | throw new Error( 51 | `'geojsonfile' parameter on server only allowed if filename starts with http(s)` 52 | ); 53 | } 54 | osmsm(params) 55 | .then((data) => res.end(data)) 56 | .catch((err) => res.status(500).end(err.toString())); 57 | }; 58 | 59 | app.get("/", (req, res) => handler(res, req.query)); 60 | app.post("/", (req, res) => handler(res, req.body)); 61 | 62 | app.get("/dynamic", (req, res) => { 63 | handler(res, { ...req.query, renderToHtml: true }) 64 | }) 65 | 66 | app.post("/dynamic", (req, res) => { 67 | handler(res, { ...req.body, renderToHtml: true }) 68 | }) 69 | 70 | export default createServer(app); 71 | -------------------------------------------------------------------------------- /src/lib.d.ts: -------------------------------------------------------------------------------- 1 | import { Control, IconOptions, PathOptions } from "leaflet"; 2 | 3 | export = _default; 4 | 5 | interface OsmStaticMapsOptions { 6 | /** 7 | * Geojson object to be rendered in the map 8 | * @defaultValue `undefined` 9 | */ 10 | geojson?: string | GeoJSON.GeoJSON; 11 | 12 | /** 13 | * Filename or url of a geojson to be rendered in the map ('-' to use stdin) 14 | * @defaultValue `undefined` 15 | */ 16 | geojsonfile?: string; 17 | 18 | /** 19 | * height in pixels of the returned img 20 | * @defaultValue `600` 21 | */ 22 | height?: number; 23 | 24 | /** 25 | * width in pixels of the returned img 26 | * @defaultValue `800` 27 | */ 28 | width?: number; 29 | 30 | /** 31 | * center of the map lon,lat floats string 32 | * @defaultValue (center of the geojson) or `'-57.9524339,-34.921779'` 33 | */ 34 | center?: string; 35 | 36 | /** 37 | * zoomlevel of the leaflet map 38 | * @defaultValue `maxZoom` 39 | */ 40 | zoom?: number; 41 | 42 | /** 43 | * max zoomlevel of the leaflet map 44 | * @defaultValue `17` 45 | */ 46 | maxZoom?: number; 47 | 48 | /** 49 | * attribution legend watermark 50 | * @defaultValue `'osm-static-maps / © OpenStreetMap contributors'` 51 | */ 52 | attribution?: string; 53 | 54 | /** 55 | * url of a tileserver 56 | * @defaultValue `'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'` 57 | */ 58 | tileserverUrl?: string; 59 | 60 | /** 61 | * url of a vector tile server (MVT style.json) 62 | * @defaultValue `undefined` 63 | */ 64 | vectorserverUrl?: string; 65 | 66 | /** 67 | * token of the vector tile server (MVT) 68 | * @defaultValue `'no-token'` 69 | */ 70 | vectorserverToken?: string; 71 | 72 | /** 73 | * returns html of the webpage containing the map (instead of a binary image) 74 | * @defaultValue `false` 75 | */ 76 | renderToHtml?: boolean; 77 | 78 | /** 79 | * format of the image returned 80 | * @defaultValue `'png'` 81 | */ 82 | type?: "jpeg" | "png"; 83 | 84 | /** 85 | * quality of the image returned (`0`-`100`, only for `jpg`) 86 | * @defaultValue `100` 87 | */ 88 | quality?: number; 89 | 90 | /** 91 | * enable lossless compression with [optipng](https://github.com/imagemin/imagemin-optipng) / [jpegtran](https://github.com/imagemin/imagemin-jpegtran) 92 | * @defaultValue `false` 93 | */ 94 | imagemin?: boolean; 95 | 96 | /** 97 | * enable losslsess compression with [oxipng](https://github.com/shssoichiro/oxipng) 98 | * @defaultValue `false` 99 | */ 100 | oxipng?: boolean; 101 | 102 | /** 103 | * render arrows to show the direction of linestrings 104 | * @defaultValue `false` 105 | */ 106 | arrows?: boolean; 107 | 108 | /** 109 | * enable render a scale ruler (boolean or [a json options object](https://leafletjs.com/reference-1.6.0.html#control-scale-option)) 110 | * @defaultValue `false` 111 | */ 112 | scale?: boolean | Control.ScaleOptions; 113 | 114 | /** 115 | * set marker icon options ([a json options object](https://leafletjs.com/reference-1.6.0.html#icon-option)) 116 | * @defaultValue `undefined` 117 | */ 118 | markerIconOptions?: IconOptions; 119 | 120 | /** 121 | * miliseconds until page load throws timeout 122 | * @defaultValue `20000` 123 | */ 124 | timeout?: number; 125 | 126 | /** 127 | * 128 | * @defaultValue `undefined` 129 | */ 130 | style?: PathOptions; 131 | 132 | /** 133 | * throw error if there is any `console.error(...)` when rendering the map image 134 | * 135 | * @defaultValue `false` 136 | */ 137 | haltOnConsoleError?: Boolean; 138 | } 139 | 140 | /** Renders a map controlled by the options passed and returns an image */ 141 | declare function _default( 142 | options?: T 143 | ): Promise; 144 | -------------------------------------------------------------------------------- /src/cli.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import { program } from "commander"; 4 | import osmsm from "./lib.js"; 5 | import packagejson from "../package.json" with { type: 'json' }; 6 | 7 | program 8 | .version(packagejson.version) 9 | .name("osmsm") 10 | .usage( 11 | "[options]\nGenerate an image of a geojson with a background map layer" 12 | ) 13 | .option("-g, --geojson ", "Geojson object to be rendered") 14 | .option("-f, --geojsonfile ", "Geojson file name to be rendered (\"-\" reads STDIN)") 15 | .option( 16 | "-H, --height ", 17 | "Height in pixels of the returned img", 18 | Number, 19 | 600 20 | ) 21 | .option( 22 | "-W, --width ", 23 | "Width in pixels of the returned img", 24 | Number, 25 | 800 26 | ) 27 | .option( 28 | "-c, --center ", 29 | "Center of the map (default: center of geojson or '-57.9524339,-34.921779'" 30 | ) 31 | .option( 32 | "-z, --zoom ", 33 | "Zoomlevel of the map (default: maxZoom)", 34 | Number 35 | ) 36 | .option("-Z, --maxZoom ", "Maximum zoomlevel of the map", Number, 17) 37 | .option( 38 | "-A, --attribution ", 39 | "Attribution legend watermark", 40 | "osm-static-maps / © OpenStreetMap contributors" 41 | ) 42 | .option( 43 | "-t, --tileserverUrl ", 44 | "Url of a tileserver", 45 | "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" 46 | ) 47 | .option( 48 | "-m, --vectorserverUrl ", 49 | "Url of a vector tile server (MVT style.json)" 50 | ) 51 | .option( 52 | "-M, --vectorserverToken ", 53 | "Token of the vector tile server (MVT)" 54 | ) 55 | .option( 56 | "-D, --renderToHtml", 57 | "Returns html of the webpage containing the leaflet map (instead of a binary image)", 58 | false 59 | ) 60 | .option("-F, --type ", "Format of the image returned", "png") 61 | .option( 62 | "-q, --quality ", 63 | "Quality of the image returned (only for -F=jpeg)", 64 | Number, 65 | 100 66 | ) 67 | .option( 68 | "-x, --imagemin", 69 | "Apply lossless compression with optipng/jpegtran", 70 | false 71 | ) 72 | .option("-X, --oxipng", "Apply lossless compression with oxipng", false) 73 | .option( 74 | "-a, --arrows", 75 | "Render arrows to show the direction of linestrings", 76 | false 77 | ) 78 | .option( 79 | "-s, --scale [json string]", 80 | "Enable render a scale ruler (see options in https://leafletjs.com/reference-1.6.0.html#control-scale-option)", 81 | false 82 | ) 83 | .option( 84 | "-k, --markerIconOptions ", 85 | "Set marker icon options (see doc in https://leafletjs.com/reference-1.6.0.html#icon-option)" 86 | ) 87 | .option( 88 | "-T, --timeout ", 89 | "Miliseconds until page load throws timeout", 90 | Number, 91 | 20000 92 | ) 93 | .option( 94 | "-S, --style ", 95 | "Set path style options (see doc in https://leafletjs.com/reference-1.6.0.html#path-option)" 96 | ) 97 | .option( 98 | "-e, --haltOnConsoleError", 99 | "throw error if there is any console.error(...) when rendering the map image", 100 | false 101 | ) 102 | .action(function(cmd) { 103 | const opts = cmd.opts(); 104 | 105 | // DEBUG 106 | // process.stderr.write(JSON.stringify(opts, undefined, 2)); 107 | // process.stderr.write("\n"); 108 | 109 | if (!["png", "jpeg"].includes(opts.type)) { 110 | process.stderr.write( 111 | '-F|--type can only have the values "png" or "jpeg"\n' 112 | ); 113 | process.exit(2); 114 | } 115 | 116 | osmsm(opts) 117 | .then(v => { 118 | process.stdout.write(v); 119 | process.stdout.end(); 120 | process.exit(0); 121 | }) 122 | .catch(e => { 123 | process.stderr.write(e.toString()); 124 | process.exit(1); 125 | }); 126 | }); 127 | 128 | program 129 | .command("serve") 130 | .option("-p, --port ", "Port number to listen") 131 | .action(async function(cmd) { 132 | const server = (await import("./server.js")).default; 133 | const port = cmd.port || process.env.PORT || 3000; 134 | server.listen(port, function() { 135 | console.log("osmsm server listening on port " + port); 136 | }); 137 | }); 138 | 139 | program.on("--help", function() { 140 | process.stdout.write("\n"); 141 | process.stdout.write("Examples: \n"); 142 | process.stdout.write( 143 | ` $ osmsm -g '{"type":"Point","coordinates":[-105.01621,39.57422]}'\n` 144 | ); 145 | process.stdout.write( 146 | ` $ osmsm -g '[{"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\n` 147 | ); 148 | process.stdout.write( 149 | ` $ osmsm -f /path/to/my_file.json\n` 150 | ); 151 | process.stdout.write( 152 | ` $ program_with_geojson_on_stdout | osmsm -f -\n` 153 | ); 154 | process.stdout.write("\n"); 155 | }); 156 | 157 | program.parse(process.argv); 158 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 4.0.2 2 | 3 | Fix vector map labels 4 | 5 | - Fix vector map labels not being rendered with 100% opacity 6 | 7 | # 4.0.1 8 | 9 | Fix vectorserverUrl 10 | 11 | - Fix vectorserverUrl option was never returning the image 12 | - Change equal default zoom for vector and raster tiles 13 | 14 | # 4.0.0 15 | 16 | Change commonjs to nodejs modules 17 | 18 | - **Breaking**: Change commonjs to nodejs modules 19 | - Upgrade all dependencies to latest versions 20 | - Fix imagemin missing binary 21 | - Change oxipng compression to level 0 22 | 23 | # 3.11.2 24 | 25 | Improve docker files 26 | 27 | - Add prod config without volumes and autoreload 28 | 29 | # 3.11.1 30 | 31 | Better dependencies pinning 32 | 33 | - Uningnored package-lock.json to better pin dependencies 34 | 35 | # 3.11.0 36 | 37 | Improve speed 38 | 39 | - Speed up results: 40 | - Add cache to resolve faster tilesets in sample-server 41 | - Correct default tile url to use https to avoid redirection 42 | - Remove unnecessary network wait. Change it to wait for map load event 43 | - Remove tile fade-in effect to be able to resolve earlier 44 | - Upgrade all dependencies to latest versions 45 | - Removed not-working heroku demo 46 | - Removed validation that broke the /dynamic endpoint 47 | 48 | # 3.10.3 49 | 50 | Support AWS functions hotfix 51 | 52 | - Move dependencies right. 53 | 54 | # 3.10.2 55 | 56 | Support AWS functions 57 | 58 | - Move dependencies to dev to conform the 50Mib limit 59 | 60 | # 3.10.1 61 | 62 | Hotfix 63 | 64 | - Fix broken local puppeteer 65 | 66 | # 3.10.0 67 | 68 | Add support to vercel api functions 69 | 70 | - Use chrome-aws-lambda as alternative to base puppeteer 71 | 72 | # 3.9.1 73 | 74 | Maintenance 75 | 76 | - Upgrade dependencies to latest versions 77 | 78 | # 3.9.0 79 | 80 | Read geojson from file or stdin 81 | 82 | - Add new option `-f` to read geojson from file, stdin (`-`) or url 83 | - Fix issue on console error misses, add `haltOnConsoleError` option 84 | - Prevent HTML/JS injection vulnerability in sample server 85 | - Upgrade dependencies 86 | 87 | # 3.8.1 88 | 89 | Maintenance 90 | 91 | - Upgrade dependencies, outstandingly puppeteer from 3.x to 5.x 92 | - Improve sample-server logging client information 93 | 94 | # 3.8.0 95 | 96 | Add styling options to features 97 | 98 | - Add per feature and global style configuration option 99 | - Add timeout option 100 | - Add Dockerfile kanji font support 101 | - Add geojson typescript type 102 | - Fix arrows argument crashing lib 103 | - Update all dependencies to the latest version 104 | 105 | # 3.7.0 106 | 107 | Add serve command to CLI 108 | 109 | - Add serve subcommand to CLI 110 | - Fix sample-server 111 | - Updated all dependencies to latest version 112 | 113 | # 3.6.0 114 | 115 | New CLI interface, puppeteer singleton 116 | 117 | - Add CLI interface 118 | - Fix sample server using too many resources, make headless browser singleton 119 | - Updated all dependencies to latest version 120 | - Refactored README 121 | - Refactored project directory structure 122 | 123 | # 3.5.1 124 | 125 | Fix geojson option 126 | 127 | - Fix geojson option being an object was not being parsed right and throwed an error 128 | 129 | # 3.5.0 130 | 131 | Add scale and marker icon options 132 | 133 | - Add scale parameter to render a scale ruler 134 | - Add marker icon options 135 | 136 | # 3.4.1 137 | 138 | Improve code reliability 139 | 140 | - Improved requirements' path resolution: use builtin require() function instead of relying in custom paths 141 | - Updated all dependencies to latest version 142 | - Fix center parameter issue in sample server 143 | 144 | # 3.4.0 145 | 146 | Add typescript definitions, allow POST in server 147 | 148 | - Add typescript definitions 149 | - Allow sample-server to use POST json enconded body to get the parameters 150 | - Allow library to be called without any arguments 151 | 152 | # 3.3.0 153 | 154 | Add arrows option on linestrings 155 | 156 | - Add `arrows` boolean option to show the direction of each linestring inside the geojson 157 | - Updated all dependencies to latest version 158 | - Improved nodemon to watch html template file 159 | - Remove annoying package-lock.json and pin all versions directly 160 | 161 | # 3.2.0 162 | 163 | Add optional lossless compresion 164 | 165 | - Add `imagemin` boolean option to lossless compress the result image using [imagemin](https://github.com/imagemin/imagemin) (optipng / jpegtran) 166 | - Add `oxipng` boolean option to lossless compress the result image using [oxipng](https://github.com/shssoichiro/oxipng) (only for png images) (searches in `/root/.cargo/bin/oxipng`, see how to install it in [Dockerfile](./Dockerfile)) 167 | 168 | # 3.1.1 169 | 170 | Bugfixing 171 | 172 | - Fix bug wrong zooming when no geojson 173 | - Default to different zoom levels depending on vector vs raster tiles 174 | 175 | # 3.1.0 176 | 177 | Add mapbox vector tiles and expose more options 178 | 179 | - Add CHANGELOG file to track version changes 180 | - Add `vectorserverUrl` and `vectorserverToken` options for taking a screenshot using Mapbox Vector Tiles (MVT) Layer (style.json) 181 | - Expose `center` option 182 | - Expose `zoom` and`maxZoom` options 183 | - Expose `attribution` option to set the legend / copyright 184 | - Expose `renderToHtml` option 185 | - Expose `type` and `quality` to control returned image format 186 | 187 | # 3.0.0 188 | 189 | Upgrade packages and improve speed 190 | 191 | - Replace unmaintained node-webshot with puppeteer 192 | - Upgrade all dependencies, including leaflet 193 | - Fix bug geojson `Point`s were not being rendered 194 | - Add docker-compose support 195 | - Upgrade heroku config to latest CEDAR stack 196 | 197 | # 2.1.0 198 | 199 | Add options 200 | 201 | - Add `tileserverUrl` option 202 | - Add Dockerfile 203 | 204 | # 2.0.0 205 | 206 | Make it reusable as a library 207 | 208 | - Refactored to be a npm library 209 | - Publish package in npm 210 | - Started using semver 211 | 212 | # 1.0.0 213 | 214 | Improve reliability for a stable release 215 | 216 | - Serve leaflet locally instead of using a cdn 217 | - Upgrade packages to latest versions 218 | - Improve readme 219 | 220 | # 0.0.1 221 | 222 | Initial useful version. 223 | 224 | - Express application that takes a screenshot of a geojson over a leafletmap with parameters `geojson`, `height`, `width` 225 | - Published in heroku 226 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # osm-static-maps 2 | 3 | Openstreetmap static maps is a nodejs lib, CLI and server open source inspired on google static map service 4 | 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. 6 | 7 | ## How to use 8 | 9 | ### 1. CLI 10 | 11 | ```bash 12 | sudo npm i -g osm-static-maps 13 | osmsm --help 14 | osmsm -g '{"type":"Point","coordinates":[-105.01621,39.57422]}' > map.png 15 | ``` 16 | 17 | * note: if you have this error trying to install globally `Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/osm-static-maps/node_modules/puppeteer/.local-chromium'`, it's caused by this pupeteer issue https://github.com/puppeteer/puppeteer/issues/367, you can workaround by installing globally with the `unsafe-perm` flag: 18 | 19 | ```bash 20 | sudo npm i -g osm-static-maps --unsafe-perm=true 21 | ``` 22 | 23 | ### 2. nodejs library 24 | 25 | ```bash 26 | npm install osm-static-maps 27 | ``` 28 | 29 | ```javascript 30 | // index.js old school 31 | osmsm = require('osm-static-maps'); 32 | osmsm({geojson: geojson}) 33 | .then(function(imageBinaryBuffer) { ... }) 34 | .catch(function(error) { ... }) 35 | 36 | // index.js modern style (also supports typescript) 37 | import osmsm from 'osm-static-maps' 38 | const imageBinaryBuffer = await osmsm({geojson}) 39 | ``` 40 | 41 | ### 3. Standalone sample server 42 | 43 | ```bash 44 | sudo npm i -g osm-static-maps 45 | osmsm serve 46 | ``` 47 | 48 | Or you can use docker-compose 49 | ```bash 50 | git clone git@github.com:jperelli/osm-static-maps.git 51 | cd osm-static-maps 52 | docker-compose up 53 | ``` 54 | 55 | ### 4. Cloud service 56 | 57 | You can use the heroku-hosted alternative directly [here](http://osm-static-maps.herokuapp.com/ "Awesome!") 58 | 59 | We are currently in the cloud beta, contact me directly at jperelli+osmsm@gmail.com so I can give you access to the cloud service. 60 | 61 | ## API Reference 62 | 63 | All parameters have a short and long version. The short version can be used only with the shell CLI. The long version can be used with the library and can be passed to the app server as GET query params, or POST json body (remember to set the header `Content-Type: application/json`) 64 | 65 | | | Parameter | Description | Default Value | 66 | | - | ---- | ---- | ---- | 67 | | g | geojson | geojson object to be rendered in the map | `undefined` | 68 | | f | geojsonfile | filename or url to read geojson data from (use '-' to read from stdin on CLI) | `undefined` | 69 | | H | height | height in pixels of the returned img | `600` | 70 | | W | width | height in pixels of the returned img | `800` | 71 | | c | center | center of the map lon,lat floats string | (center of the geojson) or `'-57.9524339,-34.921779'` | 72 | | z | zoom | zoomlevel of the leaflet map | value of `maxZoom` | 73 | | Z | maxZoom | max zoomlevel of the leaflet map | `17` | 74 | | A | attribution | attribution legend | `'osm-static-maps / © OpenStreetMap contributors'` | 75 | | t | tileserverUrl | url of a tileserver | `'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'` | 76 | | m | vectorserverUrl | url of a vector tile server (MVT style.json) | `undefined` | 77 | | M | vectorserverToken | token of the vector tile server (MVT) | `'no-token'` | 78 | | D | renderToHtml | returns html of the webpage containing the map (instead of a binary image) | `false` | 79 | | F | type | format of the image returned (`'jpeg'`/`'png'`) | `'png'` | 80 | | q | quality | quality of the image returned (`0`-`100`, only for `jpg`) | `100` | 81 | | x | imagemin | enable lossless compression with [optipng](https://github.com/imagemin/imagemin-optipng) / [jpegtran](https://github.com/imagemin/imagemin-jpegtran) | `false` | 82 | | X | oxipng | enable losslsess compression with [oxipng](https://github.com/shssoichiro/oxipng) | `false` | 83 | | a | arrows | render arrows to show the direction of linestrings | `false` | 84 | | s | scale | enable render a scale ruler (boolean or [a json options object](https://leafletjs.com/reference-1.6.0.html#control-scale-option)) | `false` | 85 | | T | timeout | miliseconds until page load throws timeout | `20000` | 86 | | k | markerIconOptions | set marker icon options ([a json options object](https://leafletjs.com/reference-1.6.0.html#icon-option)) *see note | `undefined` (leaflet's default marker) | 87 | | S | style | style to apply to each feature ([a json options object](https://leafletjs.com/reference-1.6.0.html#path-option)) *see note | `undefined` (leaflet's default) | 88 | | e | haltOnConsoleError | throw error if there is any `console.error(...)` when rendering the map image | `false` | 89 | 90 | * Note on markerIconOptions: it's also accepted a markerIconOptions attribute in the geojson feature, for example `{"type":"Point","coordinates":[-105.01621,39.57422],"markerIconOptions":{"iconUrl":"https://leafletjs.com/examples/custom-icons/leaf-red.png"}}` 91 | 92 | * Note on style: it's also accepted a pathOptions attribute in the geojson feature, for example `{"type":"Polygon","coordinates":[[[-56.698,-36.413],[-56.716,-36.348],[-56.739,-36.311]]],"pathOptions":{"color":"#FF5555"}}` (also remember that the `#` char needs to be passed as `%23` if you are using GET params) 93 | 94 | ## Design considerations & architecture 95 | 96 | [Read the blogpost](https://jperelli.com.ar/project/2019/10/01/osm-static-maps/) on the creation of this library and how it works internally 97 | 98 | ## LICENSE 99 | 100 | - GPLv2 101 | 102 | ## Credits 103 | 104 | Specially to the contributors of 105 | 106 | - OpenStreetMap 107 | - Leaflet 108 | - Puppeteer 109 | - ExpressJS 110 | - Handlebars 111 | 112 | -------------------------------------------------------------------------------- /src/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 24 | 30 | 31 | {{#if vectorserverUrl}} 32 | 35 | 39 | {{/if}} 40 | 41 | 42 | 43 |
44 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /src/lib.js: -------------------------------------------------------------------------------- 1 | import { readFileSync } from 'fs'; 2 | import http from 'http'; 3 | import https from "https"; 4 | import handlebars from 'handlebars'; 5 | import { spawn } from "child_process"; 6 | import { fileURLToPath } from 'url'; 7 | 8 | let chrome = { args: [] }; 9 | let puppeteer; 10 | 11 | if (process.env.AWS_LAMBDA_FUNCTION_VERSION) { 12 | // running on the Vercel platform. 13 | chrome = import("chrome-aws-lambda"); 14 | puppeteer = (await import("puppeteer-core")).default; 15 | } else { 16 | // running locally. 17 | puppeteer = (await import("puppeteer")).default; 18 | } 19 | 20 | function getDep(nodeModulesFile, binary = false) { 21 | const abspath = fileURLToPath(import.meta.resolve(nodeModulesFile)); 22 | if (binary) { 23 | return new Buffer.from(readFileSync(abspath), 'binary').toString('base64'); 24 | } 25 | else { 26 | return readFileSync(abspath, 'utf8'); 27 | } 28 | } 29 | 30 | const files = { 31 | leafletjs: getDep('leaflet/dist/leaflet.js'), 32 | leafletcss: getDep('leaflet/dist/leaflet.css'), 33 | leafletpolylinedecorator: getDep('leaflet-polylinedecorator/dist/leaflet.polylineDecorator.js'), 34 | mapboxjs: getDep('mapbox-gl/dist/mapbox-gl.js'), 35 | mapboxcss: getDep('mapbox-gl/dist/mapbox-gl.css'), 36 | leafletmapboxjs: getDep('mapbox-gl-leaflet/leaflet-mapbox-gl.js'), 37 | markericonpng: getDep('leaflet/dist/images/marker-icon.png', true), 38 | } 39 | const templatestr = getDep('./template.html'); 40 | const template = handlebars.compile(templatestr); 41 | 42 | 43 | function replacefiles(str) { 44 | const ff = Object.entries(files) 45 | let res = str 46 | ff.reverse() 47 | ff.forEach(([k, v]) => res = res.replace(`//${k}//`, v)) 48 | return res 49 | } 50 | 51 | class Browser { 52 | /// browser singleton 53 | constructor() { 54 | this.browser = null; 55 | } 56 | async launch() { 57 | const executablePath = await chrome.executablePath 58 | return puppeteer.launch({ 59 | args: [...chrome.args, "--no-sandbox", "--disable-setuid-sandbox"], 60 | defaultViewport: chrome.defaultViewport, 61 | executablePath, 62 | headless: true, 63 | ignoreHTTPSErrors: true, 64 | }); 65 | } 66 | async getBrowser() { 67 | if (this.openingBrowser) { 68 | throw new Error('osm-static-maps is not ready, please wait a few seconds') 69 | } 70 | if (!this.browser || !this.browser.isConnected()) { 71 | this.openingBrowser = true; 72 | try { 73 | this.browser = await this.launch(); 74 | } 75 | catch (e) { 76 | console.log(e) 77 | console.log('Error opening browser') 78 | console.log(JSON.stringify(e, undefined, 2)) 79 | } 80 | this.openingBrowser = false; 81 | } 82 | return this.browser 83 | } 84 | async getPage() { 85 | const browser = await this.getBrowser() 86 | return browser.newPage() 87 | } 88 | } 89 | const browser = new Browser(); 90 | 91 | 92 | function httpGet(url) { 93 | // from https://stackoverflow.com/a/41471647/912450 94 | const httpx = url.startsWith('https') ? https : http; 95 | return new Promise((resolve, reject) => { 96 | let req = httpx.get(url, (res) => { 97 | if (res.statusCode !== 200) { 98 | reject(`Error ${res.statusCode} trying to get geojson file from ${url}`); 99 | } 100 | res.setEncoding('utf8'); 101 | let rawData = ''; 102 | res.on('data', (chunk) => { rawData += chunk; }); 103 | res.on('end', () => resolve(rawData) ); 104 | }); 105 | req.on('error', (err) => { 106 | reject(err); 107 | }); 108 | }); 109 | } 110 | 111 | process.on("warning", (e) => console.warn(e.stack)); 112 | 113 | 114 | // add network cache to cache tiles 115 | const cache = {}; 116 | async function configCache(page) { 117 | await page.setRequestInterception(true); 118 | 119 | page.on('request', async (request) => { 120 | const url = request.url(); 121 | if (cache[url] && cache[url].expires > Date.now()) { 122 | await request.respond(cache[url]); 123 | return; 124 | } 125 | request.continue(); 126 | }); 127 | 128 | page.on('response', async (response) => { 129 | const url = response.url(); 130 | const headers = response.headers(); 131 | const cacheControl = headers['cache-control'] || ''; 132 | const maxAgeMatch = cacheControl.match(/max-age=(\d+)/); 133 | const maxAge = maxAgeMatch && maxAgeMatch.length > 1 ? parseInt(maxAgeMatch[1], 10) : 0; 134 | if (maxAge) { 135 | if (cache[url] && cache[url].expires > Date.now()) return; 136 | 137 | let buffer; 138 | try { 139 | buffer = await response.buffer(); 140 | } catch (error) { 141 | // some responses do not contain buffer and do not need to be catched 142 | return; 143 | } 144 | 145 | cache[url] = { 146 | status: response.status(), 147 | headers: response.headers(), 148 | body: buffer, 149 | expires: Date.now() + (maxAge * 1000), 150 | }; 151 | } 152 | }); 153 | } 154 | 155 | export default function(options) { 156 | return new Promise(function(resolve, reject) { 157 | // TODO: validate options to avoid template injection 158 | options = options || {}; 159 | options.geojson = (options.geojson && (typeof options.geojson === 'string' ? options.geojson : JSON.stringify(options.geojson))) || ''; 160 | options.geojsonfile = options.geojsonfile || ''; 161 | options.height = options.height || 600; 162 | options.width = options.width || 800; 163 | options.center = options.center || ''; 164 | options.zoom = options.zoom || ''; 165 | options.maxZoom = options.maxZoom || 17; 166 | options.attribution = options.attribution || 'osm-static-maps | © OpenStreetMap contributors'; 167 | options.tileserverUrl = options.tileserverUrl || 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; 168 | options.vectorserverUrl = options.vectorserverUrl || ''; 169 | options.vectorserverToken = options.vectorserverToken || 'no-token'; 170 | options.imagemin = options.imagemin || false; 171 | options.oxipng = options.oxipng || false; 172 | options.arrows = options.arrows || false; 173 | options.scale = (options.scale && (typeof options.scale === 'string' ? options.scale : JSON.stringify(options.scale))) || false; 174 | options.markerIconOptions = (options.markerIconOptions && (typeof options.markerIconOptions === 'string' ? options.markerIconOptions : JSON.stringify(options.markerIconOptions))) || false; 175 | options.style = (options.style && (typeof options.style === 'string' ? options.style : JSON.stringify(options.style))) || false; 176 | options.timeout = typeof options.timeout == undefined ? 20000 : options.timeout; 177 | options.haltOnConsoleError = !!options.haltOnConsoleError; 178 | 179 | (async () => { 180 | 181 | if (options.geojsonfile) { 182 | if (options.geojson) { 183 | throw new Error(`Only one option allowed: 'geojsonfile' or 'geojson'`) 184 | } 185 | if (options.geojsonfile.startsWith("http://") || options.geojsonfile.startsWith("https://")) { 186 | options.geojson = await httpGet(options.geojsonfile) 187 | } 188 | else { 189 | options.geojson = readFileSync( 190 | options.geojsonfile == "-" 191 | ? process.stdin.fd 192 | : options.geojsonfile, 193 | "utf8" 194 | ); 195 | } 196 | } 197 | 198 | const html = replacefiles(template(options)); 199 | 200 | if (options.renderToHtml) { 201 | return resolve(html); 202 | } 203 | 204 | const page = await browser.getPage(); 205 | await configCache(page); 206 | try { 207 | page.on('error', function (err) { reject(err.toString()) }) 208 | page.on('pageerror', function (err) { reject(err.toString()) }) 209 | if (options.haltOnConsoleError) { 210 | page.on('console', function (msg) { 211 | if (msg.type() === "error") { 212 | reject(JSON.stringify(msg)); 213 | } 214 | }) 215 | } 216 | await page.setViewport({ 217 | width: Number(options.width), 218 | height: Number(options.height) 219 | }); 220 | 221 | await page.setContent(html); 222 | await page.waitForFunction(() => window.mapRendered === true, { timeout: Number(options.timeout) }); 223 | 224 | let imageBinary = await page.screenshot({ 225 | type: options.type || 'png', 226 | quality: options.type === 'jpeg' ? Number(options.quality || 100) : undefined, 227 | fullPage: true 228 | }); 229 | 230 | if (options.imagemin) { 231 | const imagemin = (await import("imagemin")).default; 232 | const imageminJpegtran = (await import("imagemin-jpegtran")).default; 233 | const imageminOptipng = (await import("imagemin-optipng")).default; 234 | const plugins = [] 235 | if (options.type === 'jpeg') { 236 | plugins.push(imageminJpegtran()); 237 | } else { 238 | plugins.push(imageminOptipng()); 239 | } 240 | (async () => { 241 | resolve(await imagemin.buffer( 242 | Buffer.from(imageBinary), 243 | { 244 | plugins, 245 | } 246 | )) 247 | })(); 248 | } else { 249 | if (options.oxipng) { 250 | const child = spawn('/root/.cargo/bin/oxipng', ['-o0', '-s', '-']); 251 | child.stdin.on('error', function() {}); 252 | child.stdin.write(imageBinary); 253 | child.stdin.end(); 254 | let newimg = []; 255 | child.stdout.on('data', data => newimg.push(data)); 256 | child.on('close', () => resolve(Buffer.concat(newimg))); 257 | child.on('error', e => reject(e.toString())); 258 | } else { 259 | resolve(imageBinary); 260 | } 261 | } 262 | 263 | } 264 | catch(e) { 265 | page.close(); 266 | console.log("PAGE CLOSED with err" + e); 267 | throw(e); 268 | } 269 | page.close(); 270 | 271 | })().catch(reject) 272 | }); 273 | }; 274 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------