Skip to content
Advertisement

How to make to drawing a SVG with D3.js?

I’m trying to draw a map in an SVG with the GEOJSON data that I bring from this API, the SVG paths are filled with the data, however, the SVG is blank, as can be seen when executing the code below. Notice the document.write, the data is returned correctly.

JavaScript
JavaScript

I tested it with another GEOJSON file, and managed to draw in SVG as seen when executing the code below:

JavaScript
JavaScript

Does anyone know what’s wrong with the first code snippet?

Advertisement

Answer

There is no issue in the data, the problem here is just that you’re trying to map a very small region (San Francisco), unlike the world map in your second example. That said, you should set the scale and the center of the projection. In your case:

JavaScript

The resulting code:

JavaScript
JavaScript
JavaScript

But it’s way easier just using fitExtent with your SVG width and height:

JavaScript

And here is the resulting code:

JavaScript
JavaScript
JavaScript
Advertisement