0

I have a projection of a single county that is called dynamically through a function. I need to set the .scale() to match the varying sizes of counties for my particular application, however my question is also relevant to any use case where projections scales need to integrate with a dynamic environment.

Mark created an excellent example to illustrate my earlier problem of dynamically projecting counties:

function draw() {

      var topo = JSON.parse(JSON.stringify(allCounties));

      var someCounties = [24005, 24013, 24025, 24019, 24043, 24015, 24041, 24023],
        rand = someCounties[Math.floor(Math.random() * someCounties.length)];

      var geoCounty = topo.objects.counties.geometries.filter(function(d) {
        return d.id === rand;
      });

      topo.objects.counties.geometries = geoCounty;

      var projection = d3.geo.albersUsa()
        .translate([0, 0])
        .scale(20000);

      var path = d3.geo.path()
        .projection(projection);

      var county = topojson.feature(topo, topo.objects.counties),
        bounds = path.bounds(county);

      projection
        .translate([width / 2 - (bounds[0][0] + bounds[1][0]) / 2, height / 2 - (bounds[0][1] + bounds[1][1]) / 2]);

      countyPath
        .datum(county)
        .attr("class", "county")
        .attr("d", path);

      setTimeout(draw, 2000);
    }

Full code here: http://plnkr.co/edit/w3yeCT0VTlx0IlUHLZG6?p=preview

The above example has projections of the state of Maryland. My own use case is actually all counties. The counties of Maryland are relatively small, so .scale(20000) is suitable. However, other counties can be much larger, resulting in the projection to go out of the bounds of the SVG it was appended to.

So my question is thus:

Given the task of dynamic projections and a static svg of size:

var width = 500,
  height = 300;

How can I dynamically change .scale() so that the bounds of the county will maximize the svg space (vertically or horizontally) but not exceed the bounds of the svg?

It seems like a simple algebra based 'solve for X' type of problem, but I'm having immense trouble understanding how bounds even works. It seems to start in a different place with each polygon. Please advise,

Thank you

Mark
  • 106,305
  • 20
  • 172
  • 230
Arash Howaida
  • 2,575
  • 2
  • 19
  • 50
  • 2
    This is a duplicate (answered by Mr. Bostock himself!). I've applied his answer to my plunker [here](http://plnkr.co/edit/xJd2bD3z6YAx2rRSvomt?p=preview). Enjoy! – Mark Feb 01 '17 at 20:16
  • Oh that's a surprise, a pleasant one.Thank you for pointing that out to me. I phrased the question a bit differently, I suppose that's why I didn't see any immediate posts on this. Cool plunker! – Arash Howaida Feb 02 '17 at 10:57

0 Answers0