2

I like to draw a circle in each coordinate. Using only width, height, and coordinates, how do I scale the coordinates? I'm very new to D3.js and I guess I'm doing something wrong with the projection part.

var width = 200,
    height = 200;
var svg = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height);

var coordinates = [ [43.08803611,-79.06312222], 
                    [43.09453889,-79.05636667] ];

var group = svg.append('g');

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

var projectedCoordinates = [];
for (var i=0; i<coordinates.length; i++) {
    projectedCoordinates[i] = projection(coordinates[i]);
}

group.selectAll("circle")
    .data(projectedCoordinates)
    .enter()
    .append("circle")
    .attr("r",4)
    .attr("cx", function(d){ return d[0]; })
    .attr("cy", function(d){ return d[1]; });    

1 Answer 1

6

You are almost there, the only problem is that your projection is projecting the coordinates outside your drawing area. You can use the .center() function to tell the projection where the center is and .scale() to "zoom in". You should also only translate the projection by half the width and height of the container, otherwise the center will be in the bottom right corner.

The following example values should enable you to see the points:

var projection = d3.geo.mercator()
                    .center([43.09, -79.06])
                    .scale(50000)
                    .translate([width/2,height/2]);
2
  • Thanks. Assuming there are tons of coordinates, is there a good way to determine the center point and the scale factor (50000 in your suggestion)?
    – Chang
    Commented May 9, 2013 at 19:00
  • See for example this question. Commented May 9, 2013 at 19:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.