How to control the order of layers on a map in d3js

I have a simple question about creating maps with d3js. I want to make a map with two layers. One layer is the map outline (geoJson), and the other layer contains streets (topoJson). My problem is that the street layer is always loaded in front of the outline layer, regardless of which one is written in the code. I would like to have the opposite situation: the contour layer in front of the streets. I think this problem arises because both requests are asynchronous and the contour layer is loaded earlier because it is the lightest.

Here is the code ...

//Width and height
            var w = 900;
            var h = 500;

            //Define map projection
            var projection = d3.geo.transverseMercator()
                                   .center([2.5, -34.65])
                                   .rotate([61.5, 0])
                                   .scale((h * 750.5) / 3)
                                   .translate([(w/2), (h/2)]);

            //Define path generator
            var path = d3.geo.path()
                             .projection(projection);

            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            //Load in TopoJSON data
            d3.json("streets.json", function(error, topology) {


                svg.selectAll("path")
                   .data(topojson.feature(topology, topology.objects.layer1).features)
                   .enter()
                   .append("path")
                   .attr("d", path)
                   .style("fill", "white")
                   .style("stroke", "#cccccc");

            });

            //Load in GeoJSON data
            d3.json("contour.geojson", function(json) {

                //Bind data and create one path per GeoJSON feature
                svg.selectAll("path")
                   .data(json.features)
                   .enter()
                   .append("path")
                   .attr("d", path)
                   .style("fill","white")
                   .style("stroke","black")
                   .style("stroke-width",4);

            });

Can I first load the street layer, wait for the streets to be drawn, and then load the outline layer? Thanks in advance.

+4
1

g . :

var countourG = svg.append("g"),
    streetG = svg.append("g");

d3.json("streets.json", function(error, topology) {
  streetG.selectAll("path")...
});

d3.json("contour.json", function(error, topology) {
  contourG.selectAll("path")...
});
+7

Source: https://habr.com/ru/post/1525170/


All Articles