Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for OpenStreetMap #250

Merged
merged 19 commits into from
Jul 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/healthy-meals-prove.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"eleventy-plugin-embed-openstreetmap": major
"eleventy-plugin-embed-everything": minor
"eleventy-plugin-embed-everything-demo": patch
---

Add OpenStreetMap support
1 change: 1 addition & 0 deletions demo/src/index.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
This is an example site to demonstrate and test the functionality of [Embed Everything](https://gfscott.com/embed-everything).

- [Instagram example](/instagram/)
- [OpenStreetMap example](/osm/)
- [Soundcloud example](/soundcloud/)
- [Spotify example](/spotify/)
- [TED example](/ted/)
Expand Down
5 changes: 5 additions & 0 deletions demo/src/osm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: OpenStreetMap
---

https://www.openstreetmap.org/#map=16/62.1103/-7.4393
1 change: 1 addition & 0 deletions packages/everything/.eleventy.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Needs to be in global context to be accessed by module
global.instagram = require("eleventy-plugin-embed-instagram");
global.openstreetmap = require("eleventy-plugin-embed-openstreetmap");
global.soundcloud = require("eleventy-plugin-embed-soundcloud");
global.spotify = require("eleventy-plugin-embed-spotify");
global.ted = require("eleventy-plugin-embed-ted");
Expand Down
10 changes: 6 additions & 4 deletions packages/everything/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Currently, the plugin supports the following embed services (listed alphabetical

**On by default:**
- Instagram
- OpenStreetMap
- Spotify
- TikTok
- Twitch
Expand All @@ -83,7 +84,7 @@ The plugin supports a number of frequently used services by default, and they ha

You can configure which services you want active by passing an options object to the `addPlugin` function:

**Example (✨ New in 1.11.0):** configure the plugin to embed all default services _plus_ SoundCloud
**Example:** configure the plugin to embed all default services _plus_ SoundCloud

```javascript
eleventyConfig.addPlugin(embedEverything, {
Expand Down Expand Up @@ -129,10 +130,11 @@ For more about each [supported service](#supported-services), consult this table
| Service | Package | Repository | Options |
| ------- | ------- | ---------- | ------- |
| Instagram | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-instagram) | [GitHub](/packages/instagram) | [Options](/packages/instagram/lib/pluginDefaults.js) |
| OpenStreetMap | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-openstreetmap) | [GitHub](/packages/openstreetmap) | [Options](/packages/openstreetmap/lib/defaults.js) |
| SoundCloud | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-soundcloud) | [GitHub](/packages/soundcloud) | [Options](/packages/soundcloud/lib/pluginDefaults.js) |
| Spotify | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-spotify) | [GitHub](/packages/spotify) | [Options](/packages/spotify/lib/pluginDefaults.js) |
| Spotify | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-spotify) | [GitHub](/packages/spotify) | [Options](/packages/spotify/lib/defaults.js) |
| TikTok | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-tiktok) | [GitHub](/packages/tiktok) | [Options](/packages/tiktok/lib/pluginDefaults.js) |
| Twitch | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-twitch) | [GitHub](/packages/twitch) | [Options](/packages/twitch/lib/pluginDefaults.js) |
| Twitter | [npm](https://www.npmjs.com/package/eleventy-plugin-embed-twitter) | [GitHub](/packages/twitter) | [Options](/packages/twitter/lib/pluginDefaults.js) |
| Vimeo | [npm](https://www.npmjs.com/package/eleventy-plugin-vimeo-embed) | [GitHub](/packages/vimeo) | [Options](/packages/vimeo/lib/pluginDefaults.js) |
| YouTube | [npm](https://www.npmjs.com/package/eleventy-plugin-youtube-embed) | [GitHub](/packages/youtube) | [Options](/packages/youtube/lib/pluginDefaults.js) |
| Vimeo | [npm](https://www.npmjs.com/package/eleventy-plugin-vimeo-embed) | [GitHub](/packages/vimeo) | [Options](/packages/vimeo/lib/defaults.js) |
| YouTube | [npm](https://www.npmjs.com/package/eleventy-plugin-youtube-embed) | [GitHub](/packages/youtube) | [Options](/packages/youtube/lib/defaults.js) |
2 changes: 2 additions & 0 deletions packages/everything/lib/pluginDefaults.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
exports.validPlugins = [
"instagram",
"openstreetmap",
"soundcloud",
"spotify",
"ted",
Expand All @@ -22,6 +23,7 @@ exports.validPlugins = [
*/
exports.defaultPlugins = [
"instagram",
"openstreetmap",
"spotify",
"ted",
"tiktok",
Expand Down
1 change: 1 addition & 0 deletions packages/everything/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"dependencies": {
"deepmerge": "^4.3.1",
"eleventy-plugin-embed-instagram": "workspace:^",
"eleventy-plugin-embed-openstreetmap": "workspace:^",
"eleventy-plugin-embed-soundcloud": "workspace:^",
"eleventy-plugin-embed-spotify": "workspace:^",
"eleventy-plugin-embed-ted": "workspace:^",
Expand Down
6 changes: 4 additions & 2 deletions packages/everything/test/test-configOptions.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const config = require("../lib/configOptions.js");
const defaultOptions = {
activePlugins: [
"instagram",
"openstreetmap",
"spotify",
"ted",
"tiktok",
Expand All @@ -14,6 +15,7 @@ const defaultOptions = {
],
activePluginOptions: {
instagram: {options: {}},
openstreetmap: {options: {}},
spotify: {options: {}},
ted: {options: {}},
tiktok: {options: {}},
Expand Down Expand Up @@ -62,7 +64,7 @@ test(
add: ["soundcloud"],
});
let expected = clone(defaultOptions);
expected.activePlugins.splice(1, 0, "soundcloud");
expected.activePlugins = [...expected.activePlugins, "soundcloud"].sort();
expected.activePluginOptions.soundcloud = {options: {}};
t.deepEqual(output, expected);
},
Expand Down Expand Up @@ -222,7 +224,7 @@ test(
soundcloud: {options: {small: true}},
});
let expected = clone(defaultOptions);
expected.activePlugins.splice(1, 0, "soundcloud");
expected.activePlugins = [...expected.activePlugins, "soundcloud"].sort();
expected.activePluginOptions.soundcloud = {options: {small: true}};
t.deepEqual(output, expected);
},
Expand Down
77 changes: 77 additions & 0 deletions packages/openstreetmap/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# eleventy-plugin-embed-openstreetmap

[![NPM Version](https://img.shields.io/npm/v/eleventy-plugin-embed-openstreetmap?style=for-the-badge)](https://www.npmjs.com/package/eleventy-plugin-embed-openstreetmap)
[![Build test status](https://img.shields.io/github/actions/workflow/status/gfscott/eleventy-plugin-embed-everything/test.yml?branch=main&style=for-the-badge)](https://github.com/gfscott/eleventy-plugin-embed-everything/actions/workflows/test.yml?query=branch%3Amain)\
[![MIT License](https://img.shields.io/github/license/gfscott/eleventy-plugin-embed-everything?style=for-the-badge)](https://github.com/gfscott/eleventy-plugin-embed-everything/blob/main/LICENSE)
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-v2.0-ff69b4.svg?style=for-the-badge)](https://github.com/gfscott/eleventy-plugin-embed-everything/blob/main/CODE_OF_CONDUCT.md)

This [Eleventy](https://www.11ty.dev/) plugin automatically embeds OpenStreetMap maps from URLs in markdown files. It’s part of the [`eleventy-plugin-embed-everything`](https://gfscott.com/embed-everything/) project.

## Install in Eleventy

In your Eleventy project, [install the plugin](https://www.11ty.dev/docs/plugins/#adding-a-plugin) through npm:

```sh
$ npm i eleventy-plugin-embed-openstreetmap
```

Then add it to your [Eleventy config](https://www.11ty.dev/docs/config/) file (usually `.eleventy.js`):

```javascript
const embedOSM = require("eleventy-plugin-embed-openstreetmap");

module.exports = function(eleventyConfig) {
eleventyConfig.addPlugin(embedOSM);
};
```

## Usage

To place an OpenStreetMap embed into any markdown page, paste its URL into a new line. The URL should be the only thing on that line.

### Markdown file example:

```markdown
...

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vehicula, elit vel condimentum porta, purus.

https://www.openstreetmap.org/#map=13/-27.1386/-109.3388

Maecenas non velit nibh. Aenean eu justo et odio commodo ornare. In scelerisque sapien at.

...
```

### Result:

![Screenshot of OpenStreetMap view of Easter Island](https://github.com/gfscott/eleventy-plugin-embed-everything/assets/547470/0d88730a-78bf-4652-9a74-6822420d6459)


## Settings

You can configure the plugin to change its behavior by passing an options object to the `addPlugin` function:

```javascript
eleventyConfig.addPlugin(embedOSM, {
// just an example, see default values below:
embedClass: 'custom-classname'
});
```

### Plugin default options

The plugin’s default settings reside in [lib/defaults.js](lib/defaults.js). All of these values can be customized with an options object passed to the plugin.

Option | Type | Default | Notes
---|---|---|---
`embedClass` | String | `"eleventy-plugin-embed-openstreetmap"` | CSS class applied to the container `<div>` that wraps the embedded map.
`layer` | String | `mapnik` | Selected [tile layer](https://wiki.openstreetmap.org/wiki/Featured_tile_layers) style applied to the map.
`wrapperStyle` | String | `aspect-ratio: 16/9` | Inline CSS `style` parameter applied to the container `div`.

## Notes and caveats

- This plugin is deliberately designed _only_ to embed when the URL is on its own line, and not inline with other text.
- To do this, it uses a regular expression to recognize OpenStreetMap URLs, wrapped in an HTML `<p>` tag. If your Markdown parser produces any other output, it won’t be recognized.
- I’ve tried to accommodate common URL variants, but there are conceivably valid OSM URLs that wouldn’t get recognized. Please [file an issue](https://github.com/gfscott/eleventy-plugin-embed-everything/issues/new) if you run into an edge case!
- This plugin uses [transforms](https://www.11ty.dev/docs/config/#transforms), so it alters Eleventy’s HTML output as it’s generated. It doesn’t alter the source markdown.
11 changes: 11 additions & 0 deletions packages/openstreetmap/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const pattern = require("./lib/pattern.js");
const replace = require('./lib/replace.js');

module.exports = function(eleventyConfig, options = {}) {
eleventyConfig.addTransform("embedOpenStreetMap",async function(content, outputPath) {
if ( !outputPath || !outputPath.endsWith(".html")) {
return content;
}
return content.replace(pattern, (...match) => replace(match, options));
});
};
5 changes: 5 additions & 0 deletions packages/openstreetmap/lib/defaults.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
embedClass: "eleventy-plugin-embed-openstreetmap",
layer: "mapnik",
wrapperStyle: "aspect-ratio: 16/9"
}
1 change: 1 addition & 0 deletions packages/openstreetmap/lib/pattern.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

70 changes: 70 additions & 0 deletions packages/openstreetmap/lib/replace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
const defaults = require('./defaults.js');
const merge = require('deepmerge');

module.exports = function(match, options = {}) {

const config = merge(defaults, options);

const {long, lat, zoom} = match.pop();
const {long_s, lat_e, long_e, lat_s} = getBoundingBox(long, lat, zoom, 425, 350);
const bbox = encodeURIComponent(`${long_s},${lat_e},${long_e},${lat_s}`);

let out = `<div class="${config.embedClass}" style="${config.wrapperStyle}">`;
out += `<iframe width="100%" height="100%" frameborder="0" src="https://www.openstreetmap.org/export/embed.html?bbox=${bbox}&layer=${config.layer}"></iframe>`;
out += `</div>`;

return out;
}






function rad2deg(radians) {
return radians * (180/Math.PI);
}

function deg2rad(degrees) {
return degrees * (Math.PI/180);
}

function sec(num) {
return 1 / Math.cos(num);
}

function getLongLat(xtile, ytile, zoom) {
const n = Math.pow(2, zoom);
const longDegree = xtile / n * 360.0 - 180.0;
const latDegree = rad2deg(Math.atan(Math.sinh(Math.PI * (1 - 2 * ytile / n))));
return [longDegree, latDegree];
}

function getTileNumber(long, lat, zoom) {
const xtile = (long + 180)/360 * Math.pow(2, zoom);
const ytile = (1 - Math.log(Math.tan(deg2rad(lat)) + sec(deg2rad(lat)))/Math.PI)/2 * Math.pow(2, zoom);
return [xtile, ytile];
}

function getBoundingBox(long, lat, zoom, width, height) {
const [xtile, ytile] = getTileNumber(parseFloat(long), parseFloat(lat), zoom);

const tileSize = 256;

const xtile_s = (xtile * tileSize - width) / tileSize;
const ytile_s = (ytile * tileSize - height) / tileSize;
const xtile_e = (xtile * tileSize + width) / tileSize;
const ytile_e = (ytile * tileSize + height) / tileSize;

const [long_s, lat_s] = getLongLat(xtile_s, ytile_s, zoom);
const [long_e, lat_e] = getLongLat(xtile_e, ytile_e, zoom);

return {
long_s,
lat_e,
long_e,
lat_s
}
}

module.exports.getBoundingBox = getBoundingBox;
35 changes: 35 additions & 0 deletions packages/openstreetmap/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "eleventy-plugin-embed-openstreetmap",
"version": "0.1.0",
"description": "An Eleventy plugin to automatically embed OpenStreetMap maps, using just their URLs.",
"keywords": [
"11ty",
"eleventy",
"eleventy-plugin",
"openstreetmap"
],
"main": "index.js",
"scripts": {
"test": "npx ava",
"coverage": "nyc --reporter=lcov ava"
},
"files": [
"index.js",
"lib/**"
],
"author": {
"name": "Graham F. Scott",
"email": "[email protected]",
"url": "https://gfscott.com"
},
"license": "MIT",
"homepage": "https://gfscott.com/embed-everything/",
"repository": {
"type": "git",
"url": "https://github.com/gfscott/eleventy-plugin-embed-everything.git"
},
"bugs": "https://github.com/gfscott/eleventy-plugin-embed-everything/issues",
"dependencies": {
"deepmerge": "^4.3.1"
}
}
28 changes: 28 additions & 0 deletions packages/openstreetmap/test/pattern.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import test from 'ava';
import pattern from '../lib/pattern.js';
import permuteArrays from 'permute-arrays';

const base = 'openstreetmap.org';
const prefixes = ['', '//', 'www.', '//www.', 'https://', 'http://', 'https://www.', 'http://www.'];
const suffixes = [
'/#map=8/46.195/-81.362',
'/way/1147323572#map=8/46.195/-81.362',
'/search?whereami=1&query=52.147%2C104.106#map=8/46.195/-81.362'
];
// Use set to remove duplicates; slice to remove URLs without paths
const validUrls = new Set(permuteArrays(base, prefixes, suffixes).slice(prefixes.length))

for (let url of validUrls) {
test(`${url} is a valid URL`, t => {
pattern.lastIndex = 0;
t.regex(`<p>${url}</p>`, pattern);
});

test(`Expected values extracted from ${url}`, t => {
pattern.lastIndex = 0;
const { groups: { zoom, lat, long } } = pattern.exec(`<p>${url}</p>`);
t.is(zoom, '8');
t.is(lat, '46.195');
t.is(long, '-81.362');
})
}
Loading
Loading