Last active
July 7, 2016 06:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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