UNPKG

2.96 kBPlain TextView Raw
1import Point from '@mapbox/point-geometry';
2
3import mvt from '@mapbox/vector-tile';
4import type {VectorTileFeature, VectorTileLayer, VectorTile} from '@mapbox/vector-tile';
5const toGeoJSON = mvt.VectorTileFeature.prototype.toGeoJSON;
6import EXTENT from '../data/extent';
7
8// The feature type used by geojson-vt and supercluster. Should be extracted to
9// global type and used in module definitions for those two modules.
10export type Feature = {
11 type: 1;
12 id: any;
13 tags: {[_: string]: string | number | boolean};
14 geometry: Array<[number, number]>;
15} | {
16 type: 2 | 3;
17 id: any;
18 tags: {[_: string]: string | number | boolean};
19 geometry: Array<Array<[number, number]>>;
20};
21
22class FeatureWrapper implements VectorTileFeature {
23 _feature: Feature;
24
25 extent: number;
26 type: 1 | 2 | 3;
27 id: number;
28 properties: {[_: string]: string | number | boolean};
29
30 constructor(feature: Feature) {
31 this._feature = feature;
32
33 this.extent = EXTENT;
34 this.type = feature.type;
35 this.properties = feature.tags;
36
37 // If the feature has a top-level `id` property, copy it over, but only
38 // if it can be coerced to an integer, because this wrapper is used for
39 // serializing geojson feature data into vector tile PBF data, and the
40 // vector tile spec only supports integer values for feature ids --
41 // allowing non-integer values here results in a non-compliant PBF
42 // that causes an exception when it is parsed with vector-tile-js
43 if ('id' in feature && !isNaN(feature.id)) {
44 this.id = parseInt(feature.id, 10);
45 }
46 }
47
48 loadGeometry() {
49 if (this._feature.type === 1) {
50 const geometry = [];
51 for (const point of this._feature.geometry) {
52 geometry.push([new Point(point[0], point[1])]);
53 }
54 return geometry;
55 } else {
56 const geometry = [];
57 for (const ring of this._feature.geometry) {
58 const newRing = [];
59 for (const point of ring) {
60 newRing.push(new Point(point[0], point[1]));
61 }
62 geometry.push(newRing);
63 }
64 return geometry;
65 }
66 }
67
68 toGeoJSON(x: number, y: number, z: number) {
69 return toGeoJSON.call(this, x, y, z);
70 }
71}
72
73class GeoJSONWrapper implements VectorTile, VectorTileLayer {
74 layers: {[_: string]: VectorTileLayer};
75 name: string;
76 extent: number;
77 length: number;
78 _features: Array<Feature>;
79
80 constructor(features: Array<Feature>) {
81 this.layers = {'_geojsonTileLayer': this};
82 this.name = '_geojsonTileLayer';
83 this.extent = EXTENT;
84 this.length = features.length;
85 this._features = features;
86 }
87
88 feature(i: number): VectorTileFeature {
89 return new FeatureWrapper(this._features[i]);
90 }
91}
92
93export default GeoJSONWrapper;