Search code examples
d3.jsprojectionorthographic

DJ3S - Graticule removed when rotation is done in orthographic projection


I am using D3JS orthographic projection to see the world as a sphere and I have added graticule under all the coutries. Everything is fine but when I add drag mecanism to allow rotation the graticule are removed during event handling.

Here is the core code :

var width = 1000,
    height = 1000;

    var projection = d3.geo.orthographic()
        .scale(475)
        .translate([width / 2, height / 2])
        .clipAngle(90)
        .precision(.1)
        .rotate([0,0,0]);

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

    var graticule = d3.geo.graticule();

    var svg = d3.select("#map").append("svg")
        .attr("id", "world")
        .attr("width", width)
        .attr("height", height);

    // Append all meridians and parallels
    svg.append("path")
        .datum(graticule)
        .attr("class", "graticule")
        .attr("d", path);

    d3.json("world-countries.json", function(collection) {
        var countries = svg.selectAll("path")
            .data(collection.features)
            .enter().append("path")
            .attr("d", path)
            .attr("class", "country")
            .attr("id", function(d) {return d.id;});
   });

And here is the rototation :

   var λ = d3.scale.linear()
        .domain([0, width])
        .range([-180, 180]);

    var φ = d3.scale.linear()
        .domain([0, height])
        .range([90, -90]);

    var drag = d3.behavior.drag().origin(function() {
        var r = projection.rotate();
        return {
            x: λ.invert(r[0]),
            y: φ.invert(r[1])
        };
    }).on("drag", function() {
        projection.rotate([λ(d3.event.x), φ(d3.event.y)]);
        svg.selectAll("path").attr("d", path);
    });

    svg.call(drag);

This code does not work and can be see live here : http://www.datavis.fr/d3js/map-world-temperature/fullscreenBad.html

This one is working (I remove and add the graticule each time a rotation is done) : http://www.datavis.fr/d3js/map-world-temperature/fullscreen.html

Thanks for any help.


Solution

  • You definitely don't need to remove and draw all graticule again.

    You need to update it on drag.

    svg.selectAll(".graticule") //get all graticule
        .datum(graticule)
        .attr("d", path);//update the path
    

    And also on drag you updating the country path in a wrong way:

    svg.selectAll("path").attr("d", path);//this updates all the paths country +graticule which is wrong
    

    do like this (only update country not all path)

    svg.selectAll(".country").attr("d", path); //only update country
    

    working code here