Without having a sample of the json file or the version of d3 you are using it is pretty difficult to understand why the map rendering is failing, because of this I will assume the following, I think you might want to use a file similar to this one and that you are using the latest d3 version. The d3.json
function in d3 v5 is just a parsing utility built on to of fetch
as the docs explain.
The fetch() method takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init options object as the second argument (see Request).
The important part is that it returns a Promise
, now lets see the docs for d3.json
d3.json(input[, init])
Fetches the JSON file at the specified input URL. If init is specified, it is passed along to the underlying call to fetch.
The second optional argument is an init object that allows you to control a number of different settings with the fetch request.
So why the code you provided doesn't work? Well the callback you are providing is not being called at all. It is being passed as the second argument for the function, which won't do nothing at all.
The correct way to get the data is by using the Promise
returned by the function:
d3.json("url-to-retrieve")
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
});
With that in mind we just need to use the correct projection for the data and being careful of whether you are using a topojson or geojson file.
In this case this geojson file works with the geoMercator
projection.
d3.json("url-to-retrieve")
.then(data => {
var width = 960,
height = 500;
// Create a projection fitted to our width/height
var projection = d3.geoMercator()
.fitSize([width, height], data);
// Creates a new geographic path generator
var path = d3.geoPath()
.projection(projection);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
svg.append("rect")
.attr("class", "background")
.attr("fill", "#cacaca")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("id", "dmas")
.selectAll("path")
.data(data.features)
.enter()
.append("path")
.attr('fill', 'white')
.attr('stroke', '#222')
.attr('stroke-width', '2')
.attr("d", path);
})
.catch(err => {
console.log(err);
});
Here is a jsfiddle with the above code.