Files
tunmnlu/task_2/hw2_skeleton/Q5/submit4/script copy.js
louiscklaw 9035c1312b update,
2025-02-01 02:09:32 +08:00

97 lines
2.6 KiB
JavaScript

function ready(error, world, gameData) {
var games = [...new Set(gameData.map((item) => item.Game))].sort();
d3.select("#gameDropdown")
.selectAll("options")
.data(games)
.enter()
.append("option")
.text((d) => d)
.attr("value", (d) => d);
d3.select("#gameDropdown").on("change", () => {
selectGame = document.querySelector("#gameDropdown").value;
console.log(selectGame);
createMapAndLegend(world, gameData, selectGame);
});
// createMapAndLegend(world, gameData, games[0]);
svg
.append("path")
.datum(topojson.mesh(world.features, (a, b) => a.id !== b.id))
.attr("class", "names")
.attr("d", path);
}
function createMapAndLegend(world, gameData, selectedGame) {
console.log("init createMapAndLegend");
console.log({ world, gameData, selectedGame });
var ratingsData = {};
var ratings = [];
gameData.forEach((d) => (d["Average Rating"] = +d["Average Rating"]));
gameData.forEach((d) => {
if (d.Game === selectedGame) ratings.push(d["Average Rating"]);
});
var color = d3.scaleQuantile().range(colors).domain(ratings);
var legend = d3.legendColor().labelFormat(d3.format(".2f")).scale(color);
var div = d3.select("body").selectAll("#legend").attr("class", "column");
div.html("");
var legSvg = div.append("svg").attr("transform", "translate(20, 10)");
legSvg.append("g").attr("class", "legend").call(legend);
gameData.forEach((d) => {
if (d.Game === selectedGame) ratingsData[d.Country] = d;
});
world.features.forEach(
(d) =>
(ratingsData[d.properties.name] = ratingsData[d.properties.name] || {
"Average Rating": 0,
})
);
world.features.forEach(
(d) =>
(d.ratings_data = ratingsData[d.properties.name] || {
"Average Rating": 0,
})
);
svg
.attr("id", "countries")
.attr("class", "countries")
.selectAll("path")
.data(world.features)
.enter()
.append("path")
.attr("d", path)
.style("fill", (d) => {
if (ratingsData[d.properties.name]["Average Rating"] === 0) return "gray";
return color(ratingsData[d.properties.name]["Average Rating"]);
})
.style("stroke", "white")
.on("mouseover", (d) => {
console.log({ d, selectedGame });
// var rating = ratingsData[d.properties.name]["Average Rating"];
// d.rating = rating > 0 ? rating : "NA";
// d.users = ratingsData[d.properties.name]["Number of Users"] || "NA";
// d.game = selectedGame;
// tip.show(d);
// d3.select(this).style("stroke-width", 2);
})
.on("mouseout", (d) => {
tip.hide(d);
d3.select(this).style("stroke-width", 0.3);
});
}