2

I am pretty new to D3 so I may have overlooked a way to solve my problem. I have a map of the world (using geoJSON and mercator projection) and when I click on a country I want the projection to focus on the country (I am using its bounding box computed from the d3.geo.path() so it scales and translates the country to the center). See the code:

var projection = d3.geo.mercator()
                        .scale(width/7)
                        .translate([width / 2, height / 2]);

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

// relevant snippet from function clicked(d)
    // Zoom on a clicked country 
    var bounds = path.bounds(d),                // [[left, top], [right, bottom]]
        dx = bounds[1][0] - bounds[0][0],       // right - left
        dy = bounds[1][1] - bounds[0][1],       // bottom - top
        x = (bounds[0][0] + bounds[1][0]) / 2,  // (left - rigth) / 2
        y = (bounds[0][1] + bounds[1][1]) / 2,  // (top - bottom) / 2
        scale = .9 / Math.max(dx / width, dy / (height - menu_height)),
        translate = [width / 2 - scale * x, height / 2 - scale * y - menu_height / 2];

This works great except for when the selected country is split by the border of the map, e.g. as Russia in this picture

In this case, its bounding box corresponds to the width of the whole map, therefore it doesnt detect the "center" of the country and cannot translate, nor scale, the country correctly.

Is there a way to get either two bounding boxes corresponding to two parts of one country (I suppose not) or is it possible to get the leftmost and rightmost point of Russia independent of the rotation and then get their position in the current projection so I could center the country as a whole?

I am lost here so I will be very grateful for any tip.

KristinaZ
  • 41
  • 4

0 Answers0