D3: Circle SVGs stuck in Upper Left Corner of Canvas

Viewed 25

I'm having a bit of an issue where I'm trying to render nodes on specified coordinates in different locations on an Albers projection. Unfortunately, they're all rendering in the top left corner and I can't seem to figure out why. My code is as follows:

// Width and height of map
let width = 1145;
let height = 641;

// D3 Projection
let projection = d3
  .geoAlbersUsa()
  .translate([width / 2, height / 2])
  .scale(1425);

// Define path generator
let path = d3.geoPath().projection(projection);

// Create SVG element and append map to the SVG
let svg = d3
  .select("#map")
  .append("svg")
  .attr("width", width)
  .attr("height", height)
  .attr("viewBox", "0 0 " + width + " " + height)
  .attr("preserveAspectRatio", "xMidYMid meet");

// Load GeoJSON data and merge with states data
d3.json(
  "https://gist.githubusercontent.com/anonymous/9f6a63841a74562a4a7173b9f7033e83/raw/aafb03b49f258cbfeec816a7bf5c92288a06193c/us-states.json",
  function (json) {
    let repeat = {};

    // Bind the data to the SVG and create one path per GeoJSON feature
    svg
      .selectAll("path")
      .data(json.features)
      .enter()
      .append("path")
      .attr("d", path)
      .style("stroke", "#090909")
      .style("stroke-width", "1")
      .style("fill", "rgb(55, 55, 55)");

    d3.json("1499720400.json", function (data) {
      // (?) create a circle element for each object in the data array?
      svg
        .selectAll(".shapes")
        .data(data.cd)
        .enter()
        .append(function () {
          return document.createElementNS(
            "http://www.w3.org/2000/svg",
            "circle"
          );
        })
        .attr("class", "shapes");

      svg
        .selectAll("circle")
        .attr("class", "circle")
        .attr("r", "6")
        .attr("cx", function (d) {
          return projection([d.c[0], d.c[1]]);
        })
        .attr("cy", function (d) {
          return projection([d.c[0], d.c[1]]);
        });
    });
  }
);

and a quick sample of my JSON data:

{
  "cd": [
    { "c": [38.045072, -85.687697, 32.451, -67.7], "t": 1499721300 },
    { "c": [24.601, -73.466, 24.418, -73.146], "t": 1499720400 },
    { "c": [43.101, -107.525, 42.715, -107.094], "t": 1499720400 },
    { "c": [32.527, -68.553, 32.452, -67.846], "t": 1499722200 },
    { "c": [39.409, -88.855, 39.762, -88.483], "t": 1499723100 },
    { "c": [15.008, -88.971, 15.59, -88.739], "t": 1499722200 },
    { "c": [24.027, -76.526, 23.727, -76.125], "t": 1499723100 },

Does anyone know what might be the issue here?

1 Answers

It turns out that the Albers projection function returns null if it's outside the scope of accepted coordinates. D3's error messages aren't really that friendly I suppose. More info here: D3 albersUsa projection funtion return null

Related