D3JS: значение заполняется только в первой записи на карте geojson. Другие нулевые/неопределенные

avatar
PatriciaW
8 августа 2021 в 19:52
33
1
0

Я хочу заполнить области Онтарио PHU цветами в зависимости от уровня вакцинации. Заполняется только область PHU. Все остальные не определены. Я знаю, что значения ставок верны, потому что они отображаются при наведении курсора мыши. Я применил аналогичный подход к другим картам, но мне пришлось добавить к этому пару опций... Мне пришлось исправить ошибку в данных (над которой я не имел никакого контроля - где значение ключа в json было в верхнем регистре и не совсем то же самое. Я добавил подборку по возрастной группе

Есть ли у кого-нибудь предположения относительно причины?

 d3.json("/sites/default/d3_files/json/PHU_Boundary_fixed_PHUnames.json", function(PHUs) {
  PHUs = PHUs.features 
 // Load the data from the csv file 
 d3.csv(phuVaxAgeCSV, function(vaccines) {
// Load the correct phu name from the phu1phu2CSV file 
    d3.csv(phu1phu2CSV, function(phu1phu2) {
      vaccines.forEach (function(v) {  
      phu1phu2.forEach(function(d) { 
      if (v["PHU name"] == d["PHU name"]) { 
        v["PHU name"] = d.Reporting_PHU;  
      } // end if 
     }) // end phu1phu2.forEach

    vaccines = vaccines.filter(function(v) {
       var keyDate = parseDate(v.Date); 
       var daysDiff = d3.timeDay.count(keyDate, filterDate);  
       return daysDiff <= maxDays; 
     }) // end vaccines filter

    vaccines = vaccines.filter(function(v) {
      return v.Agegroup == selectedOption; 
   }) // end vaccines filter


 // add the calculated rates fields to PHUs

 PHUs.forEach (function(phu) { 
    vaccines.forEach(function(v) {
      if (phu.properties.PHU_NAME_E == v["PHU name"]) {
          phu.properties.rate = 100 * (v.Percent_fully_vaccinated);  
          phu.properties.count = 100 * (v.Percent_at_least_one_dose); 
       } // end if
     }) // end vaccines.forEach 

 // fix order of MultiPolygon and Polygon 
   
     if(phu.geometry.type == "MultiPolygon") { //
        phu.geometry.coordinates.forEach(function(polygon) {
        polygon.forEach(function(ring) {
           ring.reverse();
        })
      })
     } // end if f.geometry.type == "MultiPolygon"
    else if (phu.geometry.type == "Polygon") {
       phu.geometry.coordinates.forEach(function(ring) {
           ring.reverse();
       })  // end phu.geometry.type Polygon
    } // end if phu.geometry.type == "Polygon")

}) // end PHUs.foreach 

  // Add the polygons // PHUs is OK here - the map is drawn 
  var polygons = map.selectAll('path')
    .data(PHUs) 
    .enter()
    .append('path')
    .attr('d', path)
    .attr("fill", function(d){ 
          if (d.properties.rate == null) { 
            console.log("null", d.properties.rate) // this is undefined for all entries except one non-null value below.
            return "white"
         };
             return color(d.properties.rate); // only one here
         })
   .attr("stroke", "#222")
   .on('mouseover', tip.show)
   .on('mouseout', tip.hide)
}) 
}) 
}) 
}) 
Источник

Ответы (1)

avatar
PatriciaW
9 августа 2021 в 12:03
0

Основная проблема заключалась в том, что цикл вакцин не закрывался до конца программы.

phu1phu2.forEach(function(d) { 
        if (v["PHU name"] == d["PHU name"]) { // console.log ("equal ") // OK
         v["PHU name"] = d.Reporting_PHU;  // console.log("v[PHU_NAME] ",v["PHU_NAME"])
         } // end if 
        }) // end phu1phu2.forEach
      }) // end vaccines.forEach

Как только я исправил переменную заполнения, производительность значительно улучшилась.