Skip to content

Instantly share code, notes, and snippets.

@longhotsummer
Last active July 7, 2016 06:56
Show Gist options
  • Save longhotsummer/10286616 to your computer and use it in GitHub Desktop.
Save longhotsummer/10286616 to your computer and use it in GitHub Desktop.
Using D3, topojson and node.js to calculate the centroid of topojson features
/* A node.js script that uses D3 and topojson to calculate and output the lat/long
* coordinates of the centroid for a collection of topojson boundary features.
*/
// install using npm install d3
var d3 = require("d3");
// download from http://d3js.org/topojson.v1.min.js
var topojson = require("./topojson.v1.min.js");
// load json
var subplaces = require("./subplaces.topo.json");
subplaces = topojson.feature(subplaces, subplaces.objects.test);
var projection = d3.geo.mercator();
var path = d3.geo.path().projection(projection);
var features = subplaces.features;
for (var i = 0; i < features.length; i++) {
var feat = features[i];
// calculate the centroid (which is in pixels) and then invert back to lat/long
var centroid = projection.invert(path.centroid(feat));
// output: id, long, lat
console.log(feat.properties.SP_CODE + "," + centroid[1] + "," + centroid[0]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment