Функции D3 не работают при использовании нескольких источников данных - PullRequest
0 голосов
/ 13 июня 2018

Я адаптировал этот учебник «Создание карты мира с помощью d3, topojson и csv» в пригодную для использования версию v5: https://www.youtube.com/watch?v=aNbgrqRuoiE&t=216s

Однако проблема возникает в тот момент, когда явнести в отдельный источник данных, являющийся файлом CSV.Когда я ввожу его и проверяю данные, я получаю массив объектов, и это нормально.Но чтобы превратить местоположения в CSV в точки на карте, используя значения координат long и lat, мне, очевидно, нужно получить доступ к этим значениям столбца в CSV.В этом уроке автор делает это легко, используя следующее:

svg.selectAll("state-circle")
.data(data)
.enter().append("circle")
.attr("class", "state-circle")
.attr("r",2)
.attr("cx", function(d) {
    var coords = projection([d.long, d.lat])
    return coords[0];})
.attr("cy", function(d) {
    var coords = projection([d.long, d.lat])
    return coords[1];});

Но, учитывая версию D3, которую он использует, способ написания кода делает это простым.Я не знаю, как это сделать с помощью адаптации синтаксиса v5.

Поэтому, чтобы сделать то, что он сделал, мне нужно найти способ доступа к атрибутам широты и долготы внутри объектов.Теперь я довольно новичок в D3, но мне удалось добиться этого, используя следующий расчет (но я открыт для лучшего метода, так как я не уверен, что это технически лучший способ или что он будет работать с тем, что он сделал выше):

var long = d3.entries({longitude: true});
var lat = d3.entries({latitude: true});

Проблема в том, что этот код работает, только когда я тестирую его в отдельном файле .js, где CSV является единственным источником данных.Когда я пытаюсь запустить код внутри файла .js, который также содержит источник данных .json, он не работает.Он продолжает возвращать исходный массив объектов со всеми его атрибутами.

Это весь код, который я использую до сих пор:

var margin = {top: 50, left: 50, right: 50, bottom: 50},
        height = 400 - margin.top - margin.bottom,
        width = 1600 - margin.left - margin.right;

var svg = d3.selectAll("body")
        .append("svg")
        .attr("height", height + margin.top + margin.bottom)
        .attr("width", width + margin.left + margin.right)
        .append("g");

d3.json("https://d3js.org/world-50m.v1.json").then(function (data)
    {console.log(data);

var countries = topojson.feature(data,data.objects.countries).features;

// console.log(countries);

var projection = d3.geoMercator()
    .translate([width/2, height/2])
    .scale(100);

var path = d3.geoPath()
    .projection(projection);

svg.selectAll(".country")
    .data(countries)
    .enter().append("path")
    .attr("class", "country")
    .attr("d", path)
    .on("mouseover", function(d)
        {d3.select(this).classed("hover", true)})
    .on("mouseout", function(d)
        {d3.select(this).classed("hover", false)});
    });

    d3.csv("TData.csv", function(d) {
              return {
                city: d.City,
                continent: d.Continent,
                country: d.Country,
                dimension: d.Dimension,
                identity: d.Identity,
                score: +d.Score,
                state: d.Subdivision,
                trait: d.Trait,
                index: d.Index,
                longitude: d.Latitude,
                latitude: d.Longitude
              }
            }).then(function(data) {
                // console.log(data);

                    var long = d3.entries({longitude: true});
                    var lat = d3.entries({latitude: true});

    console.log(long);
    console.log(lat);

            });

Пример файла CSV:

City,Continent,Country,Dimension,Identity,Score,Subdivision,Trait,Index,Latitude,Longitude
Wilmington,North America,United States,Pride,1270858,45,Delaware,Ego,1,"39,7932","-75,6181"
Wilmington,North America,United States,Humility,1270858,23,Delaware,Selflessness,2,"39,7932","-75,6181"
Wilmington,North America,United States,Humility,1270858,23,Delaware,Generosity,3,"39,7932","-75,6181"
Wilmington,North America,United States,Anger,1270858,48,Delaware,Impatience,4,"39,7932","-75,6181"

1 Ответ

0 голосов
/ 14 июня 2018

С данным файлом csv вам пришлось проанализировать строковые координаты в переменной с плавающей точкой - и для этого вам также нужно заменить запятые там - следующий код работает

var margin = {top: 50, left: 50, right: 50, bottom: 50},
	height = 400 - margin.top - margin.bottom,
	width = 1600 - margin.left - margin.right;

var svg = d3.selectAll("body")
	.append("svg")
	.attr("height", height + margin.top + margin.bottom)
	.attr("width", width + margin.left + margin.right)
	.append("g");

var gBackground = svg.append("g"); // appended first
var gDataPoints = svg.append("g"); // appended second
			
d3.json("https://d3js.org/world-50m.v1.json").then(function (data) {
	console.log(data);

	var countries = topojson.feature(data,data.objects.countries).features;
	var long = d3.entries({longitude: true});
	var lat = d3.entries({latitude: true});

	console.log(long);
	console.log(lat);

	gBackground.selectAll(".country")
		.data(countries)
		.enter().append("path")
		.attr("class", "country")
		.attr("d", path)
		.on("mouseover", function(d)
			{d3.select(this).classed("hover", true)})
		.on("mouseout", function(d)
			{d3.select(this).classed("hover", false)});
});	

var projection = d3.geoMercator();
// .translate([width/2, height/2])
// .scale(100);
// need fixing - not sure why they're not working

var path = d3.geoPath()
	.projection(projection);

		
d3.csv("TruityData.csv", function(d) {
	return {
		city: d.City,
		continent: d.Continent,
		country: d.Country,
		dimension: d.Dimension,
		identity: d.Identity,
		score: +d.Score,
		state: d.Subdivision,
		trait: d.Trait,
		index: d.Index,
		latitude: d.Latitude,
		longitude: d.Longitude
	}
}).then(function(data) {
	// console.log(data[0]);
	
	gDataPoints.selectAll("state-circle")
		.data(data)
		.enter().append("circle")
		.attr("class", "state-circle")
		.attr("r",3)
		.attr("cx", function(d) {
			var dln = parseFloat(d.longitude.replace(",", "."));
			var dlt = parseFloat(d.latitude.replace(",", "."));
			var coords = projection([dln, dlt]);
			return coords[0];})
		.attr("cy", function(d) {
			var dln = parseFloat(d.longitude.replace(",", "."));
			var dlt = parseFloat(d.latitude.replace(",", "."));
			var coords = projection([dln, dlt]);
			return coords[1];});
		
});
...