Search code examples
javascriptd3.jsgeojson

D3 Map not showing up in browser on local server


I'm working on a D3 map that shows the provinces of China. I've tried a mix of several different tutorials, but I have been unsuccessful in making the map appear in browser, which uses the python local server.

I can see that the information of the map has been correctly enter into the g element, and that the GeoJSON file does include 32 provinces. I must be doing something wrong displaying it then?

Please see here for my code: https://github.com/claiye/map/blob/master/index.html It's quite messy because I've tried several different tutorials that don't work for what I am aiming for.

Please point out what stupid mistake I must be making. Your help is most kindly appreciated. Thanks in advance! :)


Solution

  • The issue was that the path created was not within the svg and g tag. Please check my two comments. I have verified below code is working.

    <!DOCTYPE html>
    <meta charset="utf-8">
    <title>Map Testing</title>
    <style>
        .province{
            fill:#ccc;
        }
    </style>
    <body>
    <script type="text/javascript" src="d3/d3.v3.js"></script>
    <script src="http://d3js.org/topojson.v1.min.js"></script>
    <script type="text/javascript">
    
        var width = 960; 
            height = 500;
    
        var svg = d3.select("body").append("svg").attr("width", width).attr("height",height);
    
        // Removed the slash before provinces.geojson
        d3.json("provinces.geojson", function(error, provinces) {
            if (error) return console.error(error);
    
            svg.append("g")
                .selectAll("path")
                .data(provinces.features)
                .enter()
                .append("path")
                .attr("class","province")
                .attr("d", d3.geo.path().projection(d3.geo.mercator().center([0,5]).scale(200).rotate([-180,0]))); // Added center and rotate here
    });
    </script>
    </body>
    <html