Reputation: 615
I have a project where i want to draw points on the San Fransico map in D3, the problem is that the point is only shown in the topleft corner.
The scale and the translate of the projection are calculated based on the coordinates.
// Set up size
var width = 1000,
height = width;
//coordinates
var lattop = 37.8423216;
var lonleft = -122.540474;
var lonright = -122.343407;
//calculate scale
var scale = 360*width/(lonright-lonleft);
//var scale = Math.min(width/ Math.PI, height/ Math.PI)
// Set up projection that map is using
var projection = d3.geo.mercator()
.scale(scale)
.translate([0,0]);
var trans = projection([lonleft, lattop]);
projection.translate([-1*trans[0],-1*trans[1]]);
var path = d3.geo.path().projection(projection);
var imagebox = d3.select("#map").append("svg").attr("width",width).attr("height",height);
How the points are drawed (all the coordinates of the points are between lattop, longleft and longright)
points = data
allDataLayer = imagebox.append("g");
var category = {}
allDataLayer.selectAll("circle")
.data(points).enter()
.append("circle")
.attr("class", "circles")
.attr("cx", function (d) { console.log(d.X); return projection(d.X); })
.attr("cy", function (d) { return projection(d.Y); })
.attr("r", "20px")
.attr("fill", "#C300C3")
.style("opacity", 0.5)
Why are these points not drawn on their coordinates on the map?
Allready viewed this answer: Stackoverflow question d3js-scale-transform and translate
Upvotes: 1
Views: 180
Reputation: 38171
You are not using your projection correctly:
return projection(d.X);
In most instances, a plain unadultered Mercator such as yours excepted, the x or y value of a projected point is dependent on both latitude and longitude. A d3 geoProjection is designed for this majority of times, and thus you must provide both latitude and longitude:
return projection([d.X,d.Y])[0] // cx
return projection([d.X,d.Y])[1] // cy
Providing one value will return a NaN value, and the SVG renderer will typically render these values as zero, meaning all your points get [0,0] centering values and will be located in the top left corner.
Upvotes: 1