tile-retriever
Version:
Load vector tiles from sources described in MapLibre style documents
1,320 lines (1,053 loc) • 37.6 kB
JavaScript
import Protobuf from 'pbf-esm';
function classifyRings(rings) {
// Classifies an array of rings into polygons with outer rings and holes
if (rings.length <= 1) return [rings];
const polygons = [];
let polygon, ccw;
rings.forEach(ring => {
const area = signedArea(ring);
if (area === 0) return;
if (ccw === undefined) ccw = area < 0;
if (ccw === area < 0) {
if (polygon) polygons.push(polygon);
polygon = [ring];
} else {
polygon.push(ring);
}
});
if (polygon) polygons.push(polygon);
return polygons;
}
function signedArea(ring) {
const xmul = (p1, p2) => (p2.x - p1.x) * (p1.y + p2.y);
const initialValue = xmul(ring[0], ring[ring.length - 1]);
return ring.slice(1) // NOTE: skips ring[0], shifts index
.reduce( (sum, p1, i) => sum + xmul(p1, ring[i]), initialValue );
}
const types = ["Unknown", "Point", "LineString", "Polygon"];
function toGeoJSON(size, sx = 0, sy = 0) {
// Input size is the side length of the (square) area over which the
// coordinate space of this tile [0, this.extent] will be rendered.
// Input sx, sy is the origin (top left corner) of the output coordinates
// within the (size x size) rendered area of the full tile.
size = size || this.extent;
const scale = size / this.extent;
let coords = this.loadGeometry();
let type = types[this.type];
function project(line) {
return line.map(p => [p.x * scale - sx, p.y * scale - sy]);
}
switch (type) {
case "Point":
coords = project( coords.map(p => p[0]) );
break;
case "LineString":
coords = coords.map(project);
break;
case "Polygon":
coords = classifyRings(coords);
coords = coords.map(polygon => polygon.map(project));
break;
}
if (coords.length === 1) {
coords = coords[0];
} else {
type = "Multi" + type;
}
const result = {
type: "Feature",
geometry: {
type: type,
coordinates: coords
},
properties: this.properties
};
if ("id" in this) result.id = this.id;
return result;
}
function VectorTileFeature(pbf, end, extent, keys, values) {
// Public
this.properties = {};
this.extent = extent;
this.type = 0;
// Private
this._pbf = pbf;
this._geometry = -1;
this._keys = keys;
this._values = values;
pbf.readFields(readFeature, this, end);
}
function readFeature(tag, feature, pbf) {
if (tag == 1) feature.id = pbf.readVarint();
else if (tag == 2) readTag(pbf, feature);
else if (tag == 3) feature.type = pbf.readVarint();
else if (tag == 4) feature._geometry = pbf.pos;
}
function readTag(pbf, feature) {
const end = pbf.readVarint() + pbf.pos;
const { _keys, _values } = feature;
while (pbf.pos < end) {
const key = _keys[pbf.readVarint()];
const value = _values[pbf.readVarint()];
feature.properties[key] = value;
}
}
VectorTileFeature.prototype.loadGeometry = function() {
const pbf = this._pbf;
pbf.pos = this._geometry;
const end = pbf.readVarint() + pbf.pos;
let cmd = 1;
let length = 0;
let x = 0;
let y = 0;
const lines = [];
let line;
while (pbf.pos < end) {
if (length <= 0) {
const cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
length = cmdLen >> 3;
}
length--;
if (cmd === 1 || cmd === 2) {
x += pbf.readSVarint();
y += pbf.readSVarint();
if (cmd === 1) { // moveTo
if (line) lines.push(line);
line = [];
}
line.push({ x, y });
} else if (cmd === 7) {
// Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90
if (line) line.push({ // closePolygon
x: line[0].x,
y: line[0].y
});
} else {
throw Error("unknown command " + cmd);
}
}
if (line) lines.push(line);
return lines;
};
VectorTileFeature.prototype.bbox = function() {
const pbf = this._pbf;
pbf.pos = this._geometry;
const end = pbf.readVarint() + pbf.pos;
let cmd = 1;
let length = 0;
let x = 0;
let y = 0;
let x1 = Infinity;
let x2 = -Infinity;
let y1 = Infinity;
let y2 = -Infinity;
while (pbf.pos < end) {
if (length <= 0) {
const cmdLen = pbf.readVarint();
cmd = cmdLen & 0x7;
length = cmdLen >> 3;
}
length--;
if (cmd === 1 || cmd === 2) {
x += pbf.readSVarint();
y += pbf.readSVarint();
if (x < x1) x1 = x;
if (x > x2) x2 = x;
if (y < y1) y1 = y;
if (y > y2) y2 = y;
} else if (cmd !== 7) {
throw Error("unknown command " + cmd);
}
}
return [x1, y1, x2, y2];
};
VectorTileFeature.types = types;
VectorTileFeature.prototype.toGeoJSON = toGeoJSON;
function VectorTileLayer(pbf, end) {
// Public
this.version = 1;
this.name = null;
this.extent = 4096;
this.length = 0;
// Private
this._pbf = pbf;
this._keys = [];
this._values = [];
this._features = [];
pbf.readFields(readLayer, this, end);
this.length = this._features.length;
}
function readLayer(tag, layer, pbf) {
if (tag === 15) layer.version = pbf.readVarint();
else if (tag === 1) layer.name = pbf.readString();
else if (tag === 5) layer.extent = pbf.readVarint();
else if (tag === 2) layer._features.push(pbf.pos);
else if (tag === 3) layer._keys.push(pbf.readString());
else if (tag === 4) layer._values.push(readValueMessage(pbf));
}
function readValueMessage(pbf) {
let value = null;
const end = pbf.readVarint() + pbf.pos;
while (pbf.pos < end) {
const tag = pbf.readVarint() >> 3;
value = tag === 1 ? pbf.readString() :
tag === 2 ? pbf.readFloat() :
tag === 3 ? pbf.readDouble() :
tag === 4 ? pbf.readVarint64() :
tag === 5 ? pbf.readVarint() :
tag === 6 ? pbf.readSVarint() :
tag === 7 ? pbf.readBoolean() : null;
}
return value;
}
// return feature 'i' from this layer as a 'VectorTileFeature'
VectorTileLayer.prototype.feature = function(i) {
const { _features, extent, _pbf, _keys, _values } = this;
const lastFeature = _features.length - 1;
if (i < 0 || i > lastFeature) throw Error("feature index out of bounds");
_pbf.pos = _features[i];
const end = _pbf.readVarint() + _pbf.pos;
return new VectorTileFeature(_pbf, end, extent, _keys, _values);
};
VectorTileLayer.prototype.toGeoJSON = function(size, sx, sy) {
const features = Array.from(Array(this._features.length), (v, i) => {
return this.feature(i).toGeoJSON(size, sx, sy);
});
return { type: "FeatureCollection", features, extent: this.extent };
};
function VectorTile(pbf, end) {
this.layers = pbf.readFields(readTile, {}, end);
}
function readTile(tag, layers, pbf) {
if (tag === 3) {
const layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);
if (layer.length) layers[layer.name] = layer;
}
}
function xhrGet(href, type, callback) {
const req = new XMLHttpRequest();
req.responseType = type;
req.onerror = errHandler;
req.onabort = errHandler;
req.onload = loadHandler;
req.open("get", href);
req.send();
function errHandler(e) {
return callback(xhrErr("ended with an ", e.type));
}
function loadHandler() {
const { responseType, status, response } = req;
const err = (responseType !== type) ?
xhrErr("Expected responseType ", type, ", got ", responseType) :
(status !== 200) ? xhrErr("HTTP ", status, " error from ", href) :
null;
return callback(err, response);
}
return req; // Request can be aborted via req.abort()
}
function xhrErr(...strings) {
return "XMLHttpRequest: " + strings.join("");
}
function initMVT(source) {
const getURL = initUrlFunc(source.tiles);
// TODO: use VectorTile.extent. Requires changes in dependencies, dependents
const size = 512;
return function(tileCoords, callback) {
const { z, x, y } = tileCoords;
const dataHref = getURL(z, x, y);
return xhrGet(dataHref, "arraybuffer", parseMVT);
function parseMVT(err, data) {
if (err) return callback(err, data);
const tile = new VectorTile(new Protobuf(data));
const json = Object.values(tile.layers)
.reduce((d, l) => (d[l.name] = l.toGeoJSON(size), d), {});
callback(null, json);
}
};
}
function initUrlFunc(endpoints) {
// Use a different endpoint for each request
let index = 0;
return function(z, x, y) {
index = (index + 1) % endpoints.length;
const endpoint = endpoints[index];
return endpoint.replace(/{z}/, z).replace(/{x}/, x).replace(/{y}/, y);
};
}
// calculate simplification data using optimized Douglas-Peucker algorithm
function simplify(coords, first, last, sqTolerance) {
var maxSqDist = sqTolerance;
var mid = (last - first) >> 1;
var minPosToMid = last - first;
var index;
var ax = coords[first];
var ay = coords[first + 1];
var bx = coords[last];
var by = coords[last + 1];
for (var i = first + 3; i < last; i += 3) {
var d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);
if (d > maxSqDist) {
index = i;
maxSqDist = d;
} else if (d === maxSqDist) {
// a workaround to ensure we choose a pivot close to the middle of the list,
// reducing recursion depth, for certain degenerate inputs
// https://github.com/mapbox/geojson-vt/issues/104
var posToMid = Math.abs(i - mid);
if (posToMid < minPosToMid) {
index = i;
minPosToMid = posToMid;
}
}
}
if (maxSqDist > sqTolerance) {
if (index - first > 3) simplify(coords, first, index, sqTolerance);
coords[index + 2] = maxSqDist;
if (last - index > 3) simplify(coords, index, last, sqTolerance);
}
}
// square distance from a point to a segment
function getSqSegDist(px, py, x, y, bx, by) {
var dx = bx - x;
var dy = by - y;
if (dx !== 0 || dy !== 0) {
var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = bx;
y = by;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = px - x;
dy = py - y;
return dx * dx + dy * dy;
}
function createFeature(id, type, geom, tags) {
var feature = {
id: typeof id === 'undefined' ? null : id,
type: type,
geometry: geom,
tags: tags,
minX: Infinity,
minY: Infinity,
maxX: -Infinity,
maxY: -Infinity
};
calcBBox(feature);
return feature;
}
function calcBBox(feature) {
var geom = feature.geometry;
var type = feature.type;
if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
calcLineBBox(feature, geom);
} else if (type === 'Polygon' || type === 'MultiLineString') {
for (var i = 0; i < geom.length; i++) {
calcLineBBox(feature, geom[i]);
}
} else if (type === 'MultiPolygon') {
for (i = 0; i < geom.length; i++) {
for (var j = 0; j < geom[i].length; j++) {
calcLineBBox(feature, geom[i][j]);
}
}
}
}
function calcLineBBox(feature, geom) {
for (var i = 0; i < geom.length; i += 3) {
feature.minX = Math.min(feature.minX, geom[i]);
feature.minY = Math.min(feature.minY, geom[i + 1]);
feature.maxX = Math.max(feature.maxX, geom[i]);
feature.maxY = Math.max(feature.maxY, geom[i + 1]);
}
}
// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data
function convert(data, options) {
var features = [];
if (data.type === 'FeatureCollection') {
for (var i = 0; i < data.features.length; i++) {
convertFeature(features, data.features[i], options, i);
}
} else if (data.type === 'Feature') {
convertFeature(features, data, options);
} else {
// single geometry or a geometry collection
convertFeature(features, {geometry: data}, options);
}
return features;
}
function convertFeature(features, geojson, options, index) {
if (!geojson.geometry) return;
var coords = geojson.geometry.coordinates;
var type = geojson.geometry.type;
var tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);
var geometry = [];
var id = geojson.id;
if (options.promoteId) {
id = geojson.properties[options.promoteId];
} else if (options.generateId) {
id = index || 0;
}
if (type === 'Point') {
convertPoint(coords, geometry);
} else if (type === 'MultiPoint') {
for (var i = 0; i < coords.length; i++) {
convertPoint(coords[i], geometry);
}
} else if (type === 'LineString') {
convertLine(coords, geometry, tolerance, false);
} else if (type === 'MultiLineString') {
if (options.lineMetrics) {
// explode into linestrings to be able to track metrics
for (i = 0; i < coords.length; i++) {
geometry = [];
convertLine(coords[i], geometry, tolerance, false);
features.push(createFeature(id, 'LineString', geometry, geojson.properties));
}
return;
} else {
convertLines(coords, geometry, tolerance, false);
}
} else if (type === 'Polygon') {
convertLines(coords, geometry, tolerance, true);
} else if (type === 'MultiPolygon') {
for (i = 0; i < coords.length; i++) {
var polygon = [];
convertLines(coords[i], polygon, tolerance, true);
geometry.push(polygon);
}
} else if (type === 'GeometryCollection') {
for (i = 0; i < geojson.geometry.geometries.length; i++) {
convertFeature(features, {
id: id,
geometry: geojson.geometry.geometries[i],
properties: geojson.properties
}, options, index);
}
return;
} else {
throw new Error('Input data is not a valid GeoJSON object.');
}
features.push(createFeature(id, type, geometry, geojson.properties));
}
function convertPoint(coords, out) {
out.push(projectX(coords[0]));
out.push(projectY(coords[1]));
out.push(0);
}
function convertLine(ring, out, tolerance, isPolygon) {
var x0, y0;
var size = 0;
for (var j = 0; j < ring.length; j++) {
var x = projectX(ring[j][0]);
var y = projectY(ring[j][1]);
out.push(x);
out.push(y);
out.push(0);
if (j > 0) {
if (isPolygon) {
size += (x0 * y - x * y0) / 2; // area
} else {
size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length
}
}
x0 = x;
y0 = y;
}
var last = out.length - 3;
out[2] = 1;
simplify(out, 0, last, tolerance);
out[last + 2] = 1;
out.size = Math.abs(size);
out.start = 0;
out.end = out.size;
}
function convertLines(rings, out, tolerance, isPolygon) {
for (var i = 0; i < rings.length; i++) {
var geom = [];
convertLine(rings[i], geom, tolerance, isPolygon);
out.push(geom);
}
}
function projectX(x) {
return x / 360 + 0.5;
}
function projectY(y) {
var sin = Math.sin(y * Math.PI / 180);
var y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;
return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;
}
/* clip features between two axis-parallel lines:
* | |
* ___|___ | /
* / | \____|____/
* | |
*/
function clip(features, scale, k1, k2, axis, minAll, maxAll, options) {
k1 /= scale;
k2 /= scale;
if (minAll >= k1 && maxAll < k2) return features; // trivial accept
else if (maxAll < k1 || minAll >= k2) return null; // trivial reject
var clipped = [];
for (var i = 0; i < features.length; i++) {
var feature = features[i];
var geometry = feature.geometry;
var type = feature.type;
var min = axis === 0 ? feature.minX : feature.minY;
var max = axis === 0 ? feature.maxX : feature.maxY;
if (min >= k1 && max < k2) { // trivial accept
clipped.push(feature);
continue;
} else if (max < k1 || min >= k2) { // trivial reject
continue;
}
var newGeometry = [];
if (type === 'Point' || type === 'MultiPoint') {
clipPoints(geometry, newGeometry, k1, k2, axis);
} else if (type === 'LineString') {
clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics);
} else if (type === 'MultiLineString') {
clipLines(geometry, newGeometry, k1, k2, axis, false);
} else if (type === 'Polygon') {
clipLines(geometry, newGeometry, k1, k2, axis, true);
} else if (type === 'MultiPolygon') {
for (var j = 0; j < geometry.length; j++) {
var polygon = [];
clipLines(geometry[j], polygon, k1, k2, axis, true);
if (polygon.length) {
newGeometry.push(polygon);
}
}
}
if (newGeometry.length) {
if (options.lineMetrics && type === 'LineString') {
for (j = 0; j < newGeometry.length; j++) {
clipped.push(createFeature(feature.id, type, newGeometry[j], feature.tags));
}
continue;
}
if (type === 'LineString' || type === 'MultiLineString') {
if (newGeometry.length === 1) {
type = 'LineString';
newGeometry = newGeometry[0];
} else {
type = 'MultiLineString';
}
}
if (type === 'Point' || type === 'MultiPoint') {
type = newGeometry.length === 3 ? 'Point' : 'MultiPoint';
}
clipped.push(createFeature(feature.id, type, newGeometry, feature.tags));
}
}
return clipped.length ? clipped : null;
}
function clipPoints(geom, newGeom, k1, k2, axis) {
for (var i = 0; i < geom.length; i += 3) {
var a = geom[i + axis];
if (a >= k1 && a <= k2) {
newGeom.push(geom[i]);
newGeom.push(geom[i + 1]);
newGeom.push(geom[i + 2]);
}
}
}
function clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {
var slice = newSlice(geom);
var intersect = axis === 0 ? intersectX : intersectY;
var len = geom.start;
var segLen, t;
for (var i = 0; i < geom.length - 3; i += 3) {
var ax = geom[i];
var ay = geom[i + 1];
var az = geom[i + 2];
var bx = geom[i + 3];
var by = geom[i + 4];
var a = axis === 0 ? ax : ay;
var b = axis === 0 ? bx : by;
var exited = false;
if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));
if (a < k1) {
// ---|--> | (line enters the clip region from the left)
if (b > k1) {
t = intersect(slice, ax, ay, bx, by, k1);
if (trackMetrics) slice.start = len + segLen * t;
}
} else if (a > k2) {
// | <--|--- (line enters the clip region from the right)
if (b < k2) {
t = intersect(slice, ax, ay, bx, by, k2);
if (trackMetrics) slice.start = len + segLen * t;
}
} else {
addPoint(slice, ax, ay, az);
}
if (b < k1 && a >= k1) {
// <--|--- | or <--|-----|--- (line exits the clip region on the left)
t = intersect(slice, ax, ay, bx, by, k1);
exited = true;
}
if (b > k2 && a <= k2) {
// | ---|--> or ---|-----|--> (line exits the clip region on the right)
t = intersect(slice, ax, ay, bx, by, k2);
exited = true;
}
if (!isPolygon && exited) {
if (trackMetrics) slice.end = len + segLen * t;
newGeom.push(slice);
slice = newSlice(geom);
}
if (trackMetrics) len += segLen;
}
// add the last point
var last = geom.length - 3;
ax = geom[last];
ay = geom[last + 1];
az = geom[last + 2];
a = axis === 0 ? ax : ay;
if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az);
// close the polygon if its endpoints are not the same after clipping
last = slice.length - 3;
if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {
addPoint(slice, slice[0], slice[1], slice[2]);
}
// add the final slice
if (slice.length) {
newGeom.push(slice);
}
}
function newSlice(line) {
var slice = [];
slice.size = line.size;
slice.start = line.start;
slice.end = line.end;
return slice;
}
function clipLines(geom, newGeom, k1, k2, axis, isPolygon) {
for (var i = 0; i < geom.length; i++) {
clipLine(geom[i], newGeom, k1, k2, axis, isPolygon, false);
}
}
function addPoint(out, x, y, z) {
out.push(x);
out.push(y);
out.push(z);
}
function intersectX(out, ax, ay, bx, by, x) {
var t = (x - ax) / (bx - ax);
out.push(x);
out.push(ay + (by - ay) * t);
out.push(1);
return t;
}
function intersectY(out, ax, ay, bx, by, y) {
var t = (y - ay) / (by - ay);
out.push(ax + (bx - ax) * t);
out.push(y);
out.push(1);
return t;
}
function wrap(features, options) {
var buffer = options.buffer / options.extent;
var merged = features;
var left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy
var right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy
if (left || right) {
merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy
if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center
if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center
}
return merged;
}
function shiftFeatureCoords(features, offset) {
var newFeatures = [];
for (var i = 0; i < features.length; i++) {
var feature = features[i],
type = feature.type;
var newGeometry;
if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {
newGeometry = shiftCoords(feature.geometry, offset);
} else if (type === 'MultiLineString' || type === 'Polygon') {
newGeometry = [];
for (var j = 0; j < feature.geometry.length; j++) {
newGeometry.push(shiftCoords(feature.geometry[j], offset));
}
} else if (type === 'MultiPolygon') {
newGeometry = [];
for (j = 0; j < feature.geometry.length; j++) {
var newPolygon = [];
for (var k = 0; k < feature.geometry[j].length; k++) {
newPolygon.push(shiftCoords(feature.geometry[j][k], offset));
}
newGeometry.push(newPolygon);
}
}
newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));
}
return newFeatures;
}
function shiftCoords(points, offset) {
var newPoints = [];
newPoints.size = points.size;
if (points.start !== undefined) {
newPoints.start = points.start;
newPoints.end = points.end;
}
for (var i = 0; i < points.length; i += 3) {
newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);
}
return newPoints;
}
// Transforms the coordinates of each feature in the given tile from
// mercator-projected space into (extent x extent) tile space.
function transformTile(tile, extent) {
if (tile.transformed) return tile;
var z2 = 1 << tile.z,
tx = tile.x,
ty = tile.y,
i, j, k;
for (i = 0; i < tile.features.length; i++) {
var feature = tile.features[i],
geom = feature.geometry,
type = feature.type;
feature.geometry = [];
if (type === 1) {
for (j = 0; j < geom.length; j += 2) {
feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));
}
} else {
for (j = 0; j < geom.length; j++) {
var ring = [];
for (k = 0; k < geom[j].length; k += 2) {
ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));
}
feature.geometry.push(ring);
}
}
}
tile.transformed = true;
return tile;
}
function transformPoint(x, y, extent, z2, tx, ty) {
return [
Math.round(extent * (x * z2 - tx)),
Math.round(extent * (y * z2 - ty))];
}
function createTile(features, z, tx, ty, options) {
var tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);
var tile = {
features: [],
numPoints: 0,
numSimplified: 0,
numFeatures: 0,
source: null,
x: tx,
y: ty,
z: z,
transformed: false,
minX: 2,
minY: 1,
maxX: -1,
maxY: 0
};
for (var i = 0; i < features.length; i++) {
tile.numFeatures++;
addFeature(tile, features[i], tolerance, options);
var minX = features[i].minX;
var minY = features[i].minY;
var maxX = features[i].maxX;
var maxY = features[i].maxY;
if (minX < tile.minX) tile.minX = minX;
if (minY < tile.minY) tile.minY = minY;
if (maxX > tile.maxX) tile.maxX = maxX;
if (maxY > tile.maxY) tile.maxY = maxY;
}
return tile;
}
function addFeature(tile, feature, tolerance, options) {
var geom = feature.geometry,
type = feature.type,
simplified = [];
if (type === 'Point' || type === 'MultiPoint') {
for (var i = 0; i < geom.length; i += 3) {
simplified.push(geom[i]);
simplified.push(geom[i + 1]);
tile.numPoints++;
tile.numSimplified++;
}
} else if (type === 'LineString') {
addLine(simplified, geom, tile, tolerance, false, false);
} else if (type === 'MultiLineString' || type === 'Polygon') {
for (i = 0; i < geom.length; i++) {
addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0);
}
} else if (type === 'MultiPolygon') {
for (var k = 0; k < geom.length; k++) {
var polygon = geom[k];
for (i = 0; i < polygon.length; i++) {
addLine(simplified, polygon[i], tile, tolerance, true, i === 0);
}
}
}
if (simplified.length) {
var tags = feature.tags || null;
if (type === 'LineString' && options.lineMetrics) {
tags = {};
for (var key in feature.tags) tags[key] = feature.tags[key];
tags['mapbox_clip_start'] = geom.start / geom.size;
tags['mapbox_clip_end'] = geom.end / geom.size;
}
var tileFeature = {
geometry: simplified,
type: type === 'Polygon' || type === 'MultiPolygon' ? 3 :
type === 'LineString' || type === 'MultiLineString' ? 2 : 1,
tags: tags
};
if (feature.id !== null) {
tileFeature.id = feature.id;
}
tile.features.push(tileFeature);
}
}
function addLine(result, geom, tile, tolerance, isPolygon, isOuter) {
var sqTolerance = tolerance * tolerance;
if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) {
tile.numPoints += geom.length / 3;
return;
}
var ring = [];
for (var i = 0; i < geom.length; i += 3) {
if (tolerance === 0 || geom[i + 2] > sqTolerance) {
tile.numSimplified++;
ring.push(geom[i]);
ring.push(geom[i + 1]);
}
tile.numPoints++;
}
if (isPolygon) rewind(ring, isOuter);
result.push(ring);
}
function rewind(ring, clockwise) {
var area = 0;
for (var i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {
area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);
}
if (area > 0 === clockwise) {
for (i = 0, len = ring.length; i < len / 2; i += 2) {
var x = ring[i];
var y = ring[i + 1];
ring[i] = ring[len - 2 - i];
ring[i + 1] = ring[len - 1 - i];
ring[len - 2 - i] = x;
ring[len - 1 - i] = y;
}
}
}
function geojsonvt(data, options) {
return new GeoJSONVT(data, options);
}
function GeoJSONVT(data, options) {
options = this.options = extend(Object.create(this.options), options);
var debug = options.debug;
if (debug) console.time('preprocess data');
if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range');
if (options.promoteId && options.generateId) throw new Error('promoteId and generateId cannot be used together.');
var features = convert(data, options);
this.tiles = {};
this.tileCoords = [];
if (debug) {
console.timeEnd('preprocess data');
console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);
console.time('generate tiles');
this.stats = {};
this.total = 0;
}
features = wrap(features, options);
// start slicing from the top tile down
if (features.length) this.splitTile(features, 0, 0, 0);
if (debug) {
if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);
console.timeEnd('generate tiles');
console.log('tiles generated:', this.total, JSON.stringify(this.stats));
}
}
GeoJSONVT.prototype.options = {
maxZoom: 14, // max zoom to preserve detail on
indexMaxZoom: 5, // max zoom in the tile index
indexMaxPoints: 100000, // max number of points per tile in the tile index
tolerance: 3, // simplification tolerance (higher means simpler)
extent: 4096, // tile extent
buffer: 64, // tile buffer on each side
lineMetrics: false, // whether to calculate line metrics
promoteId: null, // name of a feature property to be promoted to feature.id
generateId: false, // whether to generate feature ids. Cannot be used with promoteId
debug: 0 // logging level (0, 1 or 2)
};
GeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {
var stack = [features, z, x, y],
options = this.options,
debug = options.debug;
// avoid recursion by using a processing queue
while (stack.length) {
y = stack.pop();
x = stack.pop();
z = stack.pop();
features = stack.pop();
var z2 = 1 << z,
id = toID(z, x, y),
tile = this.tiles[id];
if (!tile) {
if (debug > 1) console.time('creation');
tile = this.tiles[id] = createTile(features, z, x, y, options);
this.tileCoords.push({z: z, x: x, y: y});
if (debug) {
if (debug > 1) {
console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)',
z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);
console.timeEnd('creation');
}
var key = 'z' + z;
this.stats[key] = (this.stats[key] || 0) + 1;
this.total++;
}
}
// save reference to original geometry in tile so that we can drill down later if we stop now
tile.source = features;
// if it's the first-pass tiling
if (!cz) {
// stop tiling if we reached max zoom, or if the tile is too simple
if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;
// if a drilldown to a specific tile
} else {
// stop tiling if we reached base zoom or our target tile zoom
if (z === options.maxZoom || z === cz) continue;
// stop tiling if it's not an ancestor of the target tile
var m = 1 << (cz - z);
if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m)) continue;
}
// if we slice further down, no need to keep source geometry
tile.source = null;
if (features.length === 0) continue;
if (debug > 1) console.time('clipping');
// values we'll use for clipping
var k1 = 0.5 * options.buffer / options.extent,
k2 = 0.5 - k1,
k3 = 0.5 + k1,
k4 = 1 + k1,
tl, bl, tr, br, left, right;
tl = bl = tr = br = null;
left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);
right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);
features = null;
if (left) {
tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
left = null;
}
if (right) {
tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);
br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);
right = null;
}
if (debug > 1) console.timeEnd('clipping');
stack.push(tl || [], z + 1, x * 2, y * 2);
stack.push(bl || [], z + 1, x * 2, y * 2 + 1);
stack.push(tr || [], z + 1, x * 2 + 1, y * 2);
stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);
}
};
GeoJSONVT.prototype.getTile = function (z, x, y) {
var options = this.options,
extent = options.extent,
debug = options.debug;
if (z < 0 || z > 24) return null;
var z2 = 1 << z;
x = ((x % z2) + z2) % z2; // wrap tile x coordinate
var id = toID(z, x, y);
if (this.tiles[id]) return transformTile(this.tiles[id], extent);
if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y);
var z0 = z,
x0 = x,
y0 = y,
parent;
while (!parent && z0 > 0) {
z0--;
x0 = Math.floor(x0 / 2);
y0 = Math.floor(y0 / 2);
parent = this.tiles[toID(z0, x0, y0)];
}
if (!parent || !parent.source) return null;
// if we found a parent tile containing the original geometry, we can drill down from it
if (debug > 1) console.log('found parent tile z%d-%d-%d', z0, x0, y0);
if (debug > 1) console.time('drilling down');
this.splitTile(parent.source, z0, x0, y0, z, x, y);
if (debug > 1) console.timeEnd('drilling down');
return this.tiles[id] ? transformTile(this.tiles[id], extent) : null;
};
function toID(z, x, y) {
return (((1 << z) * y + x) * 32) + z;
}
function extend(dest, src) {
for (var i in src) dest[i] = src[i];
return dest;
}
function initGeojson(source, layerID) {
const extent = 512; // TODO: reset to 4096? Then tolerance can be default 3
const indexParams = { extent, tolerance: 1 };
const tileIndex = geojsonvt(source.data, indexParams);
return function(tileCoords, callback) {
const { z, x, y } = tileCoords;
const tile = tileIndex.getTile(z, x, y);
const err = (!tile || !tile.features || !tile.features.length)
? "ERROR in GeojsonLoader for tile z, x, y = " + [z, x, y].join(", ")
: null;
const layer = { type: "FeatureCollection", extent };
if (!err) layer.features = tile.features.map(geojsonvtToJSON);
const json = { [layerID]: layer };
setTimeout(() => callback(err, json));
return { abort: () => undefined };
};
}
function geojsonvtToJSON(value) {
const { geometry, type: typeNum, tags: properties } = value;
if (!geometry) return value;
const types = ["Unknown", "Point", "LineString", "Polygon"];
const type = (geometry.length <= 1)
? types[typeNum]
: "Multi" + types[typeNum];
const coordinates =
(type == "MultiPolygon") ? [geometry] :
(type === "Point" || type === "LineString") ? geometry[0] :
geometry;
return { geometry: { type, coordinates }, properties };
}
function init(userParams) {
const { source, defaultID } = setParams(userParams);
return (source.type === "geojson")
? initGeojson(source, defaultID)
: initMVT(source);
}
function setParams(userParams) {
const { source, defaultID = "default" } = userParams;
if (typeof defaultID !== "string") fail("defaultID must be a string");
const { type, data, tiles } = source;
if (type === "geojson") {
if (!data || !["Feature", "FeatureCollection"].includes(data.type)) {
fail("no valid geojson features");
}
} else if (type === "vector") {
if (!Array.isArray(tiles) || !tiles.every(url => typeof url === "string")) {
fail("no valid tile endpoints");
}
} else {
fail("source.type must be geojson or vector");
}
return { source, defaultID };
}
function fail(message) {
throw Error("tile-retriever: " + message);
}
export { init };