Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## main
### ✨ Features and improvements
- Add ability to add a json prefix to json stringify results of nested objects in the mvt for later parsing ([#28](https://github.com/maplibre/vt-pbf/pull/28)) (by [HarelM](https://github.com/HarelM))

- _...Add new stuff here..._

### 🐞 Bug fixes
Expand Down
14 changes: 8 additions & 6 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {GeoJSONVTTile} from '@maplibre/geojson-vt';
import type {VectorTileFeatureLike, VectorTileLike, VectorTileLayerLike} from './lib/types';

interface Context {
jsonPrefix: string;
keys: string[];
values: (string | boolean | number)[];
keycache: Record<string, number>;
Expand All @@ -17,9 +18,9 @@ interface Context {
* @param tile
* @return uncompressed, pbf-serialized tile data
*/
export function fromVectorTileJs(tile: VectorTileLike): Uint8Array {
export function fromVectorTileJs(tile: VectorTileLike, jsonPrefix = ""): Uint8Array {
const out = new Pbf();
writeTile(tile, out);
writeTile(tile, out, jsonPrefix);
return out.finish();
}

Expand All @@ -42,18 +43,19 @@ export function fromGeojsonVt(layers: Record<string, GeoJSONVTTile>, options?: G
return fromVectorTileJs({ layers: l });
}

function writeTile(tile: VectorTileLike, pbf: Pbf) {
function writeTile(tile: VectorTileLike, pbf: Pbf, jsonPrefix = "") {
for (const key in tile.layers) {
pbf.writeMessage(3, writeLayer, tile.layers[key]);
pbf.writeMessage(3, (layer, pbf) => writeLayer(layer, pbf, jsonPrefix), tile.layers[key]);
}
}

function writeLayer(layer: VectorTileLayerLike, pbf: Pbf) {
function writeLayer(layer: VectorTileLayerLike, pbf: Pbf, jsonPrefix = "") {
pbf.writeVarintField(15, layer.version || 1);
pbf.writeStringField(1, layer.name || '');
pbf.writeVarintField(5, layer.extent || 4096);

const context: Context = {
jsonPrefix,
keys: [],
values: [],
keycache: {},
Expand Down Expand Up @@ -107,7 +109,7 @@ function writeProperties(context: Context, pbf: Pbf) {
pbf.writeVarint(keyIndex);

if (typeof value !== 'string' && typeof value !== 'boolean' && typeof value !== 'number') {
value = JSON.stringify(value);
value = context.jsonPrefix + JSON.stringify(value);
}
const valueKey = typeof value + ':' + value;
let valueIndex = context.valuecache[valueKey];
Expand Down
Loading
Loading