or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-mapbox--vector-tile

JavaScript library for parsing Mapbox Vector Tiles and accessing layers and features

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@mapbox/vector-tile@2.0.x

To install, run

npx @tessl/cli install tessl/npm-mapbox--vector-tile@2.0.0

0

# Vector Tile

1

2

Vector Tile is a JavaScript library for parsing Mapbox Vector Tiles and accessing their layers and features. It provides a straightforward API for loading vector tile data from Protobuf format, extracting individual layers, iterating through features, and accessing geometry and properties with GeoJSON conversion support.

3

4

## Package Information

5

6

- **Package Name**: @mapbox/vector-tile

7

- **Package Type**: npm

8

- **Language**: JavaScript (with TypeScript support)

9

- **Installation**: `npm install @mapbox/vector-tile`

10

11

## Core Imports

12

13

```javascript

14

import { VectorTile } from '@mapbox/vector-tile';

15

```

16

17

For accessing all exports:

18

19

```javascript

20

import { VectorTile, VectorTileLayer, VectorTileFeature, classifyRings } from '@mapbox/vector-tile';

21

```

22

23

For CommonJS environments:

24

25

```javascript

26

const { VectorTile, VectorTileLayer, VectorTileFeature } = require('@mapbox/vector-tile');

27

```

28

29

## Basic Usage

30

31

```javascript

32

import { VectorTile } from '@mapbox/vector-tile';

33

import Protobuf from 'pbf';

34

35

// Parse a vector tile from binary data

36

const tile = new VectorTile(new Protobuf(data));

37

38

// Access layers by name

39

const landuse = tile.layers.landuse;

40

41

// Get number of features in layer

42

console.log(landuse.length);

43

44

// Access individual features

45

const feature = landuse.feature(0);

46

47

// Get feature properties

48

console.log(feature.properties);

49

console.log(feature.type); // 0, 1, 2, or 3

50

console.log(VectorTileFeature.types[feature.type]); // "Unknown", "Point", "LineString", "Polygon"

51

52

// Load geometry as Point arrays from @mapbox/point-geometry

53

const geometry = feature.loadGeometry();

54

console.log(geometry); // Array of Point arrays

55

56

// Get bounding box

57

const bbox = feature.bbox(); // [x1, y1, x2, y2]

58

59

// Convert to GeoJSON (requires tile coordinates)

60

const geoJSON = feature.toGeoJSON(8801, 5371, 14);

61

```

62

63

For gzip-encoded tiles (common in serialtiles-spec):

64

65

```javascript

66

import { VectorTile } from '@mapbox/vector-tile';

67

import Protobuf from 'pbf';

68

import { gunzipSync } from 'zlib';

69

70

const buffer = gunzipSync(data);

71

const tile = new VectorTile(new Protobuf(buffer));

72

```

73

74

**Working with different geometry types:**

75

76

```javascript

77

// Iterate through all features in a layer

78

for (let i = 0; i < layer.length; i++) {

79

const feature = layer.feature(i);

80

81

switch (feature.type) {

82

case 1: // Point

83

console.log('Point feature:', feature.properties);

84

break;

85

case 2: // LineString

86

console.log('LineString feature:', feature.properties);

87

break;

88

case 3: // Polygon

89

console.log('Polygon feature:', feature.properties);

90

break;

91

}

92

93

// Convert any feature to GeoJSON

94

const geoJSON = feature.toGeoJSON(x, y, z);

95

}

96

97

// Use classifyRings for polygon processing

98

import { classifyRings } from '@mapbox/vector-tile';

99

const rings = feature.loadGeometry();

100

const polygons = classifyRings(rings);

101

```

102

103

## Architecture

104

105

Vector Tile is built around three main components:

106

107

- **VectorTile**: Main parser class that reads Protobuf data and exposes layers

108

- **VectorTileLayer**: Represents individual layers within a tile, providing access to features

109

- **VectorTileFeature**: Individual features with geometry, properties, and conversion methods

110

- **Utility Functions**: Helper functions for geometry processing like polygon ring classification

111

112

The library uses lazy parsing - geometry is only decoded when explicitly requested through `loadGeometry()`.

113

114

## Capabilities

115

116

### Tile Parsing

117

118

Parse binary vector tiles from Protobuf format and access contained layers.

119

120

```javascript { .api }

121

/**

122

* Main class for parsing vector tile data

123

*/

124

class VectorTile {

125

/**

126

* Parses vector tile data from Protobuf object

127

* @param pbf - Protobuf parser instance

128

* @param end - Optional end position for parsing

129

*/

130

constructor(pbf: Protobuf, end?: number);

131

132

/** Object containing all parsed layers by name */

133

layers: Record<string, VectorTileLayer>;

134

}

135

```

136

137

### Layer Access

138

139

Access and iterate through layers within a vector tile.

140

141

```javascript { .api }

142

/**

143

* Represents a single vector tile layer

144

*/

145

class VectorTileLayer {

146

/**

147

* Creates layer from Protobuf data

148

* @param pbf - Protobuf parser instance

149

* @param end - Optional end position for parsing

150

*/

151

constructor(pbf: Protobuf, end?: number);

152

153

/** Layer version number (default: 1) */

154

version: number;

155

156

/** Layer name */

157

name: string;

158

159

/** Tile extent size (default: 4096) */

160

extent: number;

161

162

/** Number of features in the layer */

163

length: number;

164

165

/**

166

* Get feature by index from the layer

167

* @param i - Feature index (0-based)

168

* @returns Feature at the specified index

169

* @throws Error if index is out of bounds

170

*/

171

feature(i: number): VectorTileFeature;

172

}

173

```

174

175

### Feature Processing

176

177

Access feature data, geometry, and properties with conversion capabilities.

178

179

```javascript { .api }

180

/**

181

* Represents a single feature with geometry and properties

182

*/

183

class VectorTileFeature {

184

/**

185

* Creates feature from Protobuf data

186

* @param pbf - Protobuf parser instance

187

* @param end - End position for parsing

188

* @param extent - Feature extent size

189

* @param keys - Property keys array

190

* @param values - Property values array

191

*/

192

constructor(

193

pbf: Protobuf,

194

end: number,

195

extent: number,

196

keys: string[],

197

values: (number | string | boolean)[]

198

);

199

200

/** Feature properties object */

201

properties: Record<string, number | string | boolean>;

202

203

/** Feature extent size */

204

extent: number;

205

206

/** Feature type: 0=Unknown, 1=Point, 2=LineString, 3=Polygon */

207

type: 0 | 1 | 2 | 3;

208

209

/** Feature identifier if present */

210

id: number | undefined;

211

212

/**

213

* Parses and returns feature geometry as Point arrays

214

* @returns Array of Point arrays representing the geometry

215

* @throws Error for unknown geometry commands

216

*/

217

loadGeometry(): Point[][];

218

219

/**

220

* Calculates and returns bounding box of the feature

221

* @returns Bounding box as [x1, y1, x2, y2]

222

*/

223

bbox(): [number, number, number, number];

224

225

/**

226

* Converts feature to GeoJSON representation

227

* @param x - Tile X coordinate

228

* @param y - Tile Y coordinate

229

* @param z - Tile zoom level

230

* @returns GeoJSON Feature object

231

* @throws Error for unknown feature types

232

*/

233

toGeoJSON(x: number, y: number, z: number): GeoJSONFeature;

234

235

/** Static array mapping type numbers to names */

236

static types: ['Unknown', 'Point', 'LineString', 'Polygon'];

237

}

238

```

239

240

### Geometry Utilities

241

242

Utility functions for processing vector tile geometry data.

243

244

```javascript { .api }

245

/**

246

* Classifies array of rings into polygons with outer rings and holes

247

* @param rings - Array of Point arrays representing rings

248

* @returns Array of polygons, each containing arrays of rings

249

*/

250

function classifyRings(rings: Point[][]): Point[][][];

251

```

252

253

## Types

254

255

```javascript { .api }

256

/**

257

* Point geometry from @mapbox/point-geometry package

258

*/

259

interface Point {

260

/** X coordinate in tile coordinate space */

261

x: number;

262

/** Y coordinate in tile coordinate space */

263

y: number;

264

/** Creates a copy of this point */

265

clone(): Point;

266

}

267

268

/**

269

* Protobuf parser from pbf package used for reading binary vector tile data

270

*/

271

interface Protobuf {

272

/** Current position in the buffer */

273

pos: number;

274

/** Read structured fields using a callback function */

275

readFields(fn: (tag: number, obj: any, pbf: Protobuf) => void, obj: any, end?: number): any;

276

/** Read variable-length integer */

277

readVarint(): number;

278

/** Read signed variable-length integer */

279

readSVarint(): number;

280

/** Read UTF-8 string */

281

readString(): string;

282

/** Read 32-bit float */

283

readFloat(): number;

284

/** Read 64-bit double */

285

readDouble(): number;

286

/** Read 64-bit variable-length integer */

287

readVarint64(): number;

288

/** Read boolean value */

289

readBoolean(): boolean;

290

}

291

292

/**

293

* GeoJSON Feature interface from @types/geojson

294

*/

295

interface GeoJSONFeature {

296

type: 'Feature';

297

geometry: GeoJSONGeometry;

298

properties: Record<string, any>;

299

id?: number | string;

300

}

301

302

interface GeoJSONGeometry {

303

type: 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon';

304

coordinates: any[];

305

}

306

```

307

308

## Error Handling

309

310

The library throws errors in several scenarios:

311

312

- **VectorTileLayer.feature()**: Throws `Error` with message "feature index out of bounds" when i < 0 or i >= layer.length

313

- **VectorTileFeature.loadGeometry()**: Throws `Error` with message "unknown command {cmd}" for invalid geometry commands (valid commands: 1=MoveTo, 2=LineTo, 7=ClosePath)

314

- **VectorTileFeature.bbox()**: Throws `Error` with message "unknown command {cmd}" for invalid geometry commands during bounding box calculation

315

- **VectorTileFeature.toGeoJSON()**: Throws `Error` with message "unknown feature type" for invalid feature.type values

316

- **Internal parsing**: Throws `Error` with message "unknown feature value" when Protobuf value parsing fails

317

318

Example error handling:

319

320

```javascript

321

try {

322

// Safely access features with bounds checking

323

if (i >= 0 && i < layer.length) {

324

const feature = layer.feature(i);

325

const geometry = feature.loadGeometry(); // May throw for corrupted geometry data

326

const bbox = feature.bbox(); // May throw for corrupted geometry data

327

const geoJSON = feature.toGeoJSON(x, y, z); // May throw for unknown feature types

328

}

329

} catch (error) {

330

console.error('Vector tile processing error:', error.message);

331

// Handle specific error types

332

if (error.message.includes('unknown command')) {

333

console.error('Corrupted geometry data detected');

334

} else if (error.message.includes('feature index out of bounds')) {

335

console.error('Invalid feature index');

336

}

337

}

338

```