user2234003
user2234003

Reputation: 21

Map NOT loading using d3.js?

This's my first attempt to use d3 for web maps and I faced weird problem even though I literally copied the same source code. However, the map won't load I don't know if the problem from the data or there's something wrong in the code. Hope someone can figure it out !!

This's the code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>D3 Test</title>
        <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

    </head>
    <body>
        <script type="text/javascript">
            d3.select("body").append("p").text("new paragraph!");

            var svg = d3.select("body").append("svg")
                .attr("width", 960)
                .attr("height",1160)

            d3.json("usa.geojson", function (data) {

                var group = svg.selectAll("g")
                    .data(data.features)
                    .enter()
                    .append("g")

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

                var areas = group.append("path")
                    .attr("d",path)
                    .attr("class", "area")
                    .attr("fill", "steelblue") 
            });

        </script>
    </body>

The geojson file:

{
"type": "FeatureCollection",
"features": [
{ "type": "Feature",
"properties": { "GEO_ID": "0400000US23", "STATE": "23", "NAME": "Maine",
"LSAD": "", "CENSUSAREA": 30842.923000 }, 
"geometry": { "type": "MultiPolygon", "coordinates":

Upvotes: 0

Views: 969

Answers (1)

altocumulus
altocumulus

Reputation: 21578

There are two issues with your code:

  1. The GeoJSON you provided via your comment/dropbox is malformed. It is cut off on line 44 for the state of arizona.

  2. You could improve on your JSON callback function to properly handle errors. As the API docs have it on d3.json():

    the callback is invoked with two arguments: the error, if any, and the parsed JSON

    You should define a callback featuring two parameters

    d3.json("usa.geojson", function (error, data) {
    

I have corrected these errors and put together a working Plunk. Please note, that in this example only a handful of states are displayed because I had to cut down the usa.geojson file to handle it on plnkr.co.

Upvotes: 1

Related Questions