Skip to content

Instantly share code, notes, and snippets.

@korczis
Last active May 8, 2016 09:10
Show Gist options
  • Save korczis/9e38f7b28ad0f0220f90a4729a404f4d to your computer and use it in GitHub Desktop.
Save korczis/9e38f7b28ad0f0220f90a4729a404f4d to your computer and use it in GitHub Desktop.
Triangulate Topojson ( => Geojson) using earcut.js
import earcut from 'earcut';
import topojson from 'topojson';
import math from 'mathjs';
const triangulateTopojson = (res) => {
const totalStart = performance.now();
const key = Object.keys(res.objects)[0];
let start = performance.now();
const geojson = topojson.mesh(res, res.objects[key]);
let diff = performance.now() - start;
console.log(`Topo - Converting topojson to geojson took ${math.round(diff, 2)} milliseconds`);
// console.log(geojson);
for (let i = 0; i < geojson.coordinates.length; i++) {
const coordinates = geojson.coordinates[i];
start = performance.now();
const data = earcut.flatten([coordinates]);
diff = performance.now() - start;
console.log(`Topo - Flattening coordinates took ${math.round(diff, 2)} milliseconds`);
// console.log(data);
start = performance.now();
const triangles = earcut(data.vertices, data.holes, data.dimensions);
diff = performance.now() - start;
console.log(`Topo - Triangulation generated ${triangles.length / 3} triangles, took ${math.round(diff, 2)} milliseconds`);
// console.log(triangles);
// const vertex = this.props.mapEngine.layer.fromLatLngToVertex(location);
const vertices = data.vertices;
start = performance.now();
const verts = [];
for (let j = 0; j < triangles.length; j += 3) {
const a = triangles[j];
const b = triangles[j + 1];
const c = triangles[j + 2];
verts.push([
[vertices[a * 2], vertices[a * 2 + 1]],
[vertices[b * 2], vertices[b * 2 + 1]],
[vertices[c * 2], vertices[c * 2 + 1]]
]);
}
diff = performance.now() - start;
console.log(`Topo - materilization of vertices took ${math.round(diff, 2)} milliseconds`);
// console.log(verts);
}
diff = performance.now() - totalStart;
console.log(`Topo - processing took ${math.round(diff, 2)} milliseconds`);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment