Skip to content

Commit

Permalink
Add example using addProtocol to transform vector tile feature proper…
Browse files Browse the repository at this point in the history
…ties (#5370)

* Add example using addProtocol to transform vector tile feature properties

* Reverse abbreviations also

* Add example image

* Make cspell happy

* Address review comment
  • Loading branch information
neodescis authored Jan 17, 2025
1 parent d015c01 commit 3f28408
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
66 changes: 66 additions & 0 deletions test/examples/feature-properties-transform.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Use addProtocol to Transform Feature Properties</title>
<meta property="og:description" content="Reverse country names with addProtocol in plain JavaScript." />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../../dist/maplibre-gl.css" />
<script src="../../dist/maplibre-gl-dev.js"></script>
<style>
body { margin: 0; padding: 0; }
html, body, #map { height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script type="module">
import Protobuf from 'https://unpkg.com/[email protected]/index.js';
import {VectorTile} from 'https://esm.run/@mapbox/[email protected]/index.js';
import tileToProtobuf from 'https://esm.run/[email protected]/index.js';

const protocol = 'reverse';
maplibregl.addProtocol(protocol, (request) => {
const url = request.url.replace(protocol + '://', '');
return fetch(url)
.then((response) => response.arrayBuffer())
.then((data) => new VectorTile(new Protobuf(data)))
.then((tile) => ({
layers: Object.entries(tile.layers).reduce((acc, [layerId, layer]) => ({
...acc,
[layerId]: {
...layer,
feature: (index) => {
const feature = layer.feature(index);
if (feature.properties && typeof feature.properties['NAME'] === 'string') {
feature.properties['NAME'] = feature.properties['NAME'].split('').reverse().join('');
}
if (feature.properties && typeof feature.properties['ABBREV'] === 'string') {
feature.properties['ABBREV'] = feature.properties['ABBREV'].split('').reverse().join('');
}
return feature;
}
}
}), {})
}))
.then((tile) => tileToProtobuf(tile).buffer)
.then((data) => ({ data }));
});

const map = new maplibregl.Map({
container: 'map',
style: 'https://demotiles.maplibre.org/style.json',
center: [8, 47],
zoom: 5,
hash: 'map'
});

map.setTransformRequest((url, resourceType) => {
if (url.startsWith('https://demotiles.maplibre.org/tiles/') && resourceType === 'Tile') {
return { url: protocol + '://' + url };
}
return undefined;
});
</script>
</body>
</html>

0 comments on commit 3f28408

Please sign in to comment.