Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a responsive map using d3

Tags:

d3.js

I'm trying to make my map responsive, so it'd be resized according to the browser window size. This is what I have so far,

style.css

#mapbox {
border:2px solid #000;
width:960px;
height:550px;
background:#FFFFFF;
}

viz.js

var margin = {top: 10, left: 10, bottom: 10, right: 10},
width = parseInt(d3.select('#mapbox').style('width')), 
width = width - margin.left - margin.right, 
mapRatio = .5, 
height = width * mapRatio;
.
.
d3.select(window).on('resize', resize);
.
.
function resize(){  
    width = parseInt(d3.select('#mapbox').style('width'));
    width = width - margin.left - margin.right;
    height = width * mapRatio;


        projection.translate([width / 2, height / 2])
                .scale(width);

        svg.style('width', width + 'px')
            .style('height', height + 'px');

}

When I resize the window, its still keeping the same width and height for my svg container. I guess thats because, in resize function, I'm getting the width and height from the CSS which will be the same whether I resize the window right?

I'm stuck here, am I missing anything obvious? would be great if you have any pointers for me to get this working.

I'm pretty much following the following example,

like image 453
genwip Avatar asked Jan 02 '14 14:01

genwip


1 Answers

I set the svg like so to have a responsive resize:

var svg = d3.select("body")
        .append("div")
        .attr("id", "svg")
        .append("svg")
        .attr("viewBox", "0 0 " + width + " " + height )
        .attr("preserveAspectRatio", "xMinYMin");

And then set the css like so:

#svg {
    width:100%;
    height: auto;
}
like image 75
tomtomtom Avatar answered Oct 05 '22 11:10

tomtomtom