问题
I am using Alan McConchie's block for a basic mercator map in d3. I've gotten it to work locally but am trying to filter the map to exclude certain countries (Antarctica for example).
I don't want to simply remove it from the json file in case I ever need to bring it back and would rather find a non-destructive solution. From my digging, I think there is a way to filter using the code below in d3 based on country code but can't get it to work based on the example I'm using. Where do I include the filter? Before the map has been drawn? After the data has loaded?
Any better solutions for removing countries?
.data(geo_data.features.filter(d => d.id !== "ATA))
回答1:
Array.prototype.filter does not filter in-place:
filter() does not mutate the array on which it is called.
You'll have to reassign the value. For instance:
geojson.features = geojson.features.filter(d => d.id !== "ATA");
Here is the bl.ocks with that change (no Antarctica anymore): http://bl.ocks.org/anonymous/8ef6910d243e4f7a200cd6c231eb44f1/e63d0a10b4629cdee795660c9fc542207d7dc82f
However, this will remove Antarctica from the loaded data. As you want a non-destructive solution, do a deep clone first and then use the filter:
var filteredGeojson = JSON.parse(JSON.stringify(geojson));
filteredGeojson.features = filteredGeojson.features.filter(d => d.id !== "ATA");
Finally, for using your snippet...
.data(geojson.features.filter(d => d.id !== "ATA"))
... which, by the way, works just fine, you'll have to create an "enter" selection:
svg.selectAll(null)
.data(geojson.features.filter(d => d.id !== "ATA"))
.enter()
.append("path")
.attr("d", function(d){
return path(d)})
});
The problem, as you can see, is that each country will be a separate path, and I'm not sure if that's what you want: http://bl.ocks.org/anonymous/ae26c13f2ed863afbb905f598a48a0e3/3d7323cf9f016c0e19aa1c1d876e492715105819
来源:https://stackoverflow.com/questions/48228666/filtering-d3-mercator-map