d3.js Map (<svg>) Auto Fit into Parent Container and Resize with Window

前端 未结 5 2114
时光取名叫无心
时光取名叫无心 2020-12-23 16:54

UPDATE: I have posted and accepted a fully working solution in the answers section. Any code in this section is to be used as reference for comparison to your own NO

5条回答
  •  礼貌的吻别
    2020-12-23 17:37

    COMPLETE SOLUTION:

    Here's the solution which will resize the map AFTER the user has released the edge of the window to resize it, and center it in the parent container.


    function draw(ht) {
        $("#mapContainer").html("");
        map = d3.select("svg");
        var width = $("svg").parent().width();
        var height = ht;
    
        // I discovered that the unscaled equirectangular map is 640x360. Thus, we
        // should scale our map accordingly. Depending on the width ratio of the new
        // container, the scale will be this ratio * 100. You could also use the height 
        // instead. The aspect ratio of an equirectangular map is 2:1, so that's why
        // our height is half of our width.
    
        projection = d3.geo.equirectangular().scale((width/640)*100).translate([width/2, height/2]);
        var path = d3.geo.path().projection(projection);
        d3.json('plugins/maps/world.json', function(collection) {
            map.selectAll('path').data(collection.features).enter()
                .append('path')
                .attr('d', path)
                .attr("width", width)
                .attr("height", width/2);
        });
    }
    draw($("#mapContainer").width()/2);
    

    $(window).resize(function() {
        if(this.resizeTO) clearTimeout(this.resizeTO);
        this.resizeTO = setTimeout(function() {
            $(this).trigger('resizeEnd');
        }, 500);
    });
    
    $(window).bind('resizeEnd', function() {
        var height = $("#mapContainer").width()/2;
        $("#mapContainer svg").css("height", height);
        draw(height);
    });
    

提交回复
热议问题