block by emeeks 9908143

Handcrafting TopoJSON

Full Screen

My attempt at creating topojson from d3.geom.voronoi output and then merging it. Ran afoul of identifying shared faces and then winding order, I think.

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<body onload="vorToTopo()">
  <svg style="height:1000px;width:1000px;"c height="1000" width="1000">
  </svg>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v1.min.js"></script>
<script src="vorpoly.js"></script>
<script>
 
function vorToTopo() {
topoCollection = {type: "Topology", objects: {voronoi: {type: "GeometryCollection", geometries: []}},arcs:[]};
  arcHash = {};
  topoArcs = [];
  geomHash = {};
  
  function RN(num) {
    return Math.floor(num * 10) / 10;
  }
  for (x in vorPolys) {
    geomHash[x] = [];
    var polyObject = {type: "Polygon", properties: {id: x},id: parseInt(x), arcs: []};
    for (y in vorPolys[x]) {
      var hashVal = "0-0-0-0";
      var reverseVal = "0-0-0-0";
      var nextVal = parseInt(y) + 1;
      if (nextVal == vorPolys[x].length) {
	nextVal = 0;
      }
      
      hashVal = RN(vorPolys[x][y][0]) + "-" + RN(vorPolys[x][y][1]) + "-" + RN(vorPolys[x][nextVal][0]) + "-" + RN(vorPolys[x][nextVal][1])
      reverseVal = RN(vorPolys[x][nextVal][0]) + "-" + RN(vorPolys[x][nextVal][1]) + "-" + RN(vorPolys[x][y][0]) + "-" + RN(vorPolys[x][y][1])

      if (!arcHash[hashVal] && !arcHash[reverseVal]) {
	arcHash[hashVal] = topoArcs.length;
	arcHash[reverseVal] = topoArcs.length;
	topoArcs.push([[RN(vorPolys[x][nextVal][0]),RN(vorPolys[x][nextVal][1])],[RN(vorPolys[x][y][0]),RN(vorPolys[x][y][1])]]);
    }
    else {
	console.log("old");      
    }
    if (geomHash[x].indexOf(arcHash[hashVal]) == -1 && geomHash[x].indexOf(arcHash[reverseVal]) == -1) {
      	geomHash[x].push(arcHash[hashVal] || arcHash[reverseVal]);
    }
      if (nextVal == 0) {
	break;
      }

    }
    polyObject.arcs = [geomHash[x]];
    topoCollection.objects.voronoi.geometries.push(polyObject);
  }
  topoCollection.arcs = topoArcs;
  topoFeatures = topojson.feature(topoCollection, topoCollection.objects.voronoi).features;  

  d3.select("svg").insert("g", "#sitesG").attr("id", "voronoiG")
//        .datum(topojson.merge(topoCollection, topoCollection.objects.voronoi.geometries))
        .datum(topojson.merge(topoCollection, topoCollection.objects.voronoi.geometries.filter(function(d,i) { return i < 300})))
	.selectAll("path.voronoi")
	.data(function(d) {return d.coordinates})
      .enter().append("path")
        .style("fill", "red")
        .style("stroke", "black")
        .style("stroke-width", "1px")
        .attr("d", function (d) {return "M" + d.join("L") + "Z";})

}

 
</script>
</body>