| 2 | import Protobuf from 'pbf'; |
| 3 | import type { ITileSource } from '../interface'; |
| 4 | export default class VectorSource implements ITileSource { |
| 5 | private vectorTile: VectorTile; |
| 6 | private vectorLayerCache: { |
| 7 | [key: string]: Array<GeoJSON.Feature>; |
| 8 | } = {}; |
| 9 | private x: number; |
| 10 | private y: number; |
| 11 | private z: number; |
| 12 | |
| 13 | constructor(data: ArrayBuffer, x: number, y: number, z: number) { |
| 14 | this.x = x; |
| 15 | this.y = y; |
| 16 | this.z = z; |
| 17 | this.vectorTile = new VectorTile(new Protobuf(data)) as VectorTile; |
| 18 | } |
| 19 | |
| 20 | public getTileData(sourceLayer: string) { |
| 21 | if (!sourceLayer || !this.vectorTile.layers[sourceLayer]) { |
| 22 | return []; |
| 23 | } |
| 24 | // 优先走缓存 |
| 25 | if (this.vectorLayerCache[sourceLayer]) { |
| 26 | return this.vectorLayerCache[sourceLayer]; |
| 27 | } |
| 28 | |
| 29 | const vectorTile = this.vectorTile.layers[sourceLayer]; |
| 30 | |
| 31 | // @ts-ignore |
| 32 | if (Array.isArray(vectorTile.features)) { |
| 33 | // 数据不需要被解析 geojson-vt 类型 |
| 34 | // @ts-ignore |
| 35 | this.vectorLayerCache[sourceLayer] = vectorTile.features; |
| 36 | // @ts-ignore |
| 37 | return vectorTile.features; |
| 38 | } |
| 39 | |
| 40 | const features: Array<GeoJSON.Feature> = []; |
| 41 | for (let i = 0; i < vectorTile.length; i++) { |
| 42 | const vectorTileFeature = vectorTile.feature(i); |
| 43 | const feature = vectorTileFeature.toGeoJSON(this.x, this.y, this.z); |
| 44 | features.push({ |
| 45 | ...feature, |
| 46 | properties: { |
| 47 | id: feature.id, |
| 48 | ...feature.properties, |
| 49 | }, |
| 50 | }); |
| 51 | } |
| 52 | this.vectorLayerCache[sourceLayer] = features; |
| 53 | return features; |
| 54 | } |
| 55 | public getFeatureById() { |
| 56 | throw new Error('Method not implemented.'); |
| 57 | } |
| 58 | } |
nothing calls this directly
no outgoing calls
no test coverage detected