Search code examples
javascriptd3.jsprojection

D3 albersUsa projection funtion return null


I'm pretty new to D3 and I'm trying to set point on a map.

I'm confused as I created a projection with this code:

var projection = d3.geo
      .albersUsa()
      .scale(500)
      .translate([el.clientWidth / 2, el.clientHeight / 2]);

I use this projection to draw a map and it works fine.

But then whenever I call projection([10, 20]) it returns null whichever values I'm passing in.

What is my error?


Solution

  • From the documentation

    # projection(location)

    […] May return null if the specified location has no defined projected position, such as when the location is outside the clipping bounds of the projection.

    The Albers USA projection is defined only within its borders and will yield null for coordinates outside the well-defined area.

    See this comparison of calls to projection(location) using [10,20], which is not valid, and [-110,40], which is a valid point:

    var projection = d3.geo
          .albersUsa()
          .scale(500)
          .translate([960, 500]);
          
    d3.selectAll("p")
        .data([[10,20],[-110,40]])
      .enter().append("p")
        .text(function(d) { return d + ": " + projection(d); });
    
     
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>