Search code examples
jsond3.jsgeojsongeomap

D3 add graticule and geojson


When adding D3 graticule first and then calling d3.json , the very first feature within json doesn't show on the map. If I add d3.graticule within d3.json after appending paths, graticule will be drawn on top of the features, which is not what I wanted. Here is my JavaScript file:

$(document).ready(function (){

$('.aToolTip').tooltip();
$('.aPopOver').popover();

// D3 Mapping Starts Here
var h = $('#myMap').height();
var w = $('#myMap').width();

console.log("h = " + h , ",  w = " + w);

$('svg').attr('width', w)
        .attr('height', h);

var aSVG = d3.select("#aSVGElement");

var aProjection = d3.geo.mercator()
                    .rotate([-135, 24])
                    .scale(600)
                    .translate([w/2, h/2]);

var path = d3.geo.path()
                .projection(aProjection);

var graticule = d3.geo.graticule()
                    .step([10, 10]);

aSVG.append("path")
        .datum(graticule)
        .attr("class", "graticule")
        .attr("d", path);

d3.json("js/Australia.json", function(error, json){

    aSVG.selectAll("path")
        .data(json.features)
        .enter()
        .append("path")
        .attr("d", path);    

}); // end d3.json

});// end document ready 

Solution

  • The first feature doesn't show up if you're drawing the grid first because you're selecting paths, of which the grid is one. This means that the first data element (i.e. the first feature) is matched to the existing path and not part of the .enter() selection.

    To fix this, simply assign a class to your feature paths and select accordingly:

    aSVG.selectAll("path.feature")
        .data(json.features)
        .enter()
        .append("path")
        .attr("class", "feature")
        .attr("d", path);