Skip to main content
edited tags
Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
added 399 characters in body
Source Link
obrob
  • 151
  • 3

EDIT: I checked my code with the provided sample JSON. I noticed that the function playButtonSlider() is moving the slider-handle way to fast. The JSON I use for my project is significantly larger and the slider-handle is moving reasonable slower. So something is definitely not coded well with the function playButtonSlider(). But I don't know a different approach to get the same effect.

sample JSON

      // Slider
  $("#slider").slider({
          value: 2005,
          min: 2005,
          max: 2015,
          step: 0.101,
          create: function(event, ui) {
              setSliderTicks(event.target);
          },
      })
      .each(function() {
          var opt = $(this).data().uiSlider.options;
          var vals = opt.max - opt.min;
          for (var i = 0; i <= vals; i++) {
              var el = $('<label>' + (i + opt.min) + '</label>').css('left', (i / vals * 100) + '%');
              $("#slider").append(el);
          }
      });

  function setSliderTicks(el) {
      var $slider = $(el);
      var max = $slider.slider("option", "max");
      var min = $slider.slider("option", "min");
      var spacing = 100 / (max - min);

      $slider.find('.ui-slider-tick-mark').remove();
      for (var i = 1; i < max - min; i++) {
          $('<span class="ui-slider-tick-mark"></span>').css('left', (spacing * i) + '%').appendTo($slider);
      }
  }
  // Responsive Design
  var windowWidth = window.innerWidth;
  var windowHeight = window.innerHeight;

  var wrapperWidth = 0.9 * windowWidth;
  var wrapperHeight;

  if (windowWidth < windowHeight) {
    wrapperHeight = 0.5 * windowHeight;
  } else {
    wrapperHeight = 0.75 * windowHeight;
  }

  $(".wrapper").css("width", wrapperWidth);
  $(".wrapper").css("height", wrapperHeight);

  // Map EU
  var svgMapWidth =  (0.65 * wrapperWidth)  - 4;
  var svgMapHeight = wrapperHeight - 4;

  var myProjection = d3.geoMercator()
      .center([8.00, 57.00])
      .scale(500)
      .translate([svgMapWidth / 2, svgMapHeight / 2]);

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

  var color = d3.scaleThreshold()
      .domain([0, 2, 4, 6, 8, 10, 15, 20, 25, 50])
      .range(["#006837", "#1a9850", "#66bd63", "#a6d96a", "#d9ef8b", "#fee08b", "#fdae61", "#f46d43", "#d73027", "#a50026", "#808080"]);

  var svgEurope = d3.select("#svgMap").append("svg")
      .attr("width", svgMapWidth)
      .attr("height", svgMapHeight);

  var g = svgEurope.append("g");

  var zoom = d3.zoom()
      .scaleExtent([0.25, 8])
      .on("zoom", zoomed);

  svgEurope.call(zoom);

  d3.queue()
    .defer(d3.json, "data/sampleData.json")
    .await(initializeData);

  function initializeData(error, euRegionsJSON) {
    if (error) throw error;
    $('#slider').slider().bind('slidechange',e => renderMap(e,euRegionsJSON, sliderValue)); //same as $('#slider').slider().bind('slidechange',function e() {return renderMap(e,euRegionsJSON, sliderValue)});
    $('#slider').trigger('slidechange');
  };

  var sliderValue = 2005;sliderValue;

  $('#slider').slider().bind('slidechange', function(event, ui) {
      sliderValue = $('#slider').slider("value");
      sliderValue = Math.floor(sliderValue);
      $("#currentYear").text(sliderValue);
  });

  $("#playButtonSlider").on("click",playButtonSlider);
  function playButtonSlider() {
    function startTimer(counter) {
      if(counter <= 10) {
        setTimeout(function(){
          sliderValue = $("#slider").slider('value',2005+counter);
          counter += 0.1;01;
          startTimer(counter);
        },110);
      }
    }
    startTimer(0);
  }

  function renderMap(error, euRegionsJSON, sliderValue) {
    g.selectAll(".euMap").remove();
    g.selectAll("path")
        .data(euRegionsJSON.features)
        .enter().append("path")
        .attr("d", geoPath)
        .attr("class", "euMap")
        .attr("fill", function(d) {return color(d.properties[sliderValue]);})
        .style("stroke", "black")
        .style("stroke-width", "0.4px")
        .on("click",function(d) {
            highlight(this);
            setInfoBoxContent(d);
            createPlot(d);
        });
  }

  function highlight(mapClickedPath){
    d3.selectAll('path').style('fill',null);
    d3.select(mapClickedPath).style("fill", "#3333ff");
  }

  function setInfoBoxContent(mapClickedFeature) {
    $('#regionName').text(mapClickedFeature.properties.Region);
    $('#unemploymentRate').text(mapClickedFeature.properties[sliderValue]);
  }

  function zoomed() {
    g.style("stroke-width", 1.5 / d3.event.transform.k + "px");
    g.attr("transform", d3.event.transform);
  }

  $("#resetButton").on("click",reset);
  function reset(){
    svgEurope.transition().call(zoom.transform, d3.zoomIdentity);
    d3.selectAll('path').style('fill',null);
    $('#regionName').text("Europe");
    $('#unemploymentRate').text("100");
  }

  // Barplot
  var margin = {top: 10, right: 20, bottom: 35, left: 20};

  var svgPlotWidth = (0.33 * wrapperWidth) - margin.left - margin.right;
  var svgPlotHeight = 250 - margin.top - margin.bottom;

  var svgEuropeDiagramm = d3.select("#svgPlot").append("svg")
      .attr("width", svgPlotWidth + margin.left + margin.right)
      .attr("height", svgPlotHeight + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var x = d3.scaleBand()
            .rangeRound([0, svgPlotWidth])
            .padding(0.25);
  var y = d3.scaleLinear()
            .rangeRound([svgPlotHeight, 0]);

  function createPlot(mapClickedFeature) {

    var getFeatureEntries = d3.entries(mapClickedFeature.properties)
    var featureEntries = [];

    for (var i=0;i<=10;i++){
      if (getFeatureEntries[i].value == "NA") {
        getFeatureEntries[i].value = 0;
        featureEntries.push(getFeatureEntries[i])
      } else {
        featureEntries.push(getFeatureEntries[i])
      }
    }

    x.domain(featureEntries.map(function(d) { return d.key; }));
    y.domain([0, 50]);

    svgEuropeDiagramm.selectAll(".euPlot").remove();
    svgEuropeDiagramm.selectAll(".euPlot")
        .data(featureEntries)
        .enter().append("rect")
        .attr("class", "euPlot")
        .attr("x", function(d) { return x(d.key); })
        .attr("width", x.bandwidth())
        .attr("y", function(d) { return y(d.value); })
        .attr("height", function(d) { return svgPlotHeight - y(d.value); });

    svgEuropeDiagramm.selectAll(".xAxis").remove();
    svgEuropeDiagramm.append("g")
        .attr("transform", "translate(0," + svgPlotHeight + ")")
        .attr("class","xAxis")
        .call(d3.axisBottom(x))
      .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(90)")
        .style("text-anchor", "start");

    svgEuropeDiagramm.selectAll(".yAxis").remove();
    svgEuropeDiagramm.append("g")
        .attr("class","yAxis")
        .call(d3.axisLeft(y));
  }

sample JSON

      // Slider
  $("#slider").slider({
          value: 2005,
          min: 2005,
          max: 2015,
          step: 0.1,
          create: function(event, ui) {
              setSliderTicks(event.target);
          },
      })
      .each(function() {
          var opt = $(this).data().uiSlider.options;
          var vals = opt.max - opt.min;
          for (var i = 0; i <= vals; i++) {
              var el = $('<label>' + (i + opt.min) + '</label>').css('left', (i / vals * 100) + '%');
              $("#slider").append(el);
          }
      });

  function setSliderTicks(el) {
      var $slider = $(el);
      var max = $slider.slider("option", "max");
      var min = $slider.slider("option", "min");
      var spacing = 100 / (max - min);

      $slider.find('.ui-slider-tick-mark').remove();
      for (var i = 1; i < max - min; i++) {
          $('<span class="ui-slider-tick-mark"></span>').css('left', (spacing * i) + '%').appendTo($slider);
      }
  }
  // Responsive Design
  var windowWidth = window.innerWidth;
  var windowHeight = window.innerHeight;

  var wrapperWidth = 0.9 * windowWidth;
  var wrapperHeight;

  if (windowWidth < windowHeight) {
    wrapperHeight = 0.5 * windowHeight;
  } else {
    wrapperHeight = 0.75 * windowHeight;
  }

  $(".wrapper").css("width", wrapperWidth);
  $(".wrapper").css("height", wrapperHeight);

  // Map EU
  var svgMapWidth =  (0.65 * wrapperWidth)  - 4;
  var svgMapHeight = wrapperHeight - 4;

  var myProjection = d3.geoMercator()
      .center([8.00, 57.00])
      .scale(500)
      .translate([svgMapWidth / 2, svgMapHeight / 2]);

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

  var color = d3.scaleThreshold()
      .domain([0, 2, 4, 6, 8, 10, 15, 20, 25, 50])
      .range(["#006837", "#1a9850", "#66bd63", "#a6d96a", "#d9ef8b", "#fee08b", "#fdae61", "#f46d43", "#d73027", "#a50026", "#808080"]);

  var svgEurope = d3.select("#svgMap").append("svg")
      .attr("width", svgMapWidth)
      .attr("height", svgMapHeight);

  var g = svgEurope.append("g");

  var zoom = d3.zoom()
      .scaleExtent([0.25, 8])
      .on("zoom", zoomed);

  svgEurope.call(zoom);

  d3.queue()
    .defer(d3.json, "data/sampleData.json")
    .await(initializeData);

  function initializeData(error, euRegionsJSON) {
    if (error) throw error;
    $('#slider').slider().bind('slidechange',e => renderMap(e,euRegionsJSON, sliderValue)); //same as $('#slider').slider().bind('slidechange',function e() {return renderMap(e,euRegionsJSON, sliderValue)});
    $('#slider').trigger('slidechange');
  };

  var sliderValue = 2005;

  $('#slider').slider().bind('slidechange', function(event, ui) {
      sliderValue = $('#slider').slider("value");
      sliderValue = Math.floor(sliderValue);
      $("#currentYear").text(sliderValue);
  });

  $("#playButtonSlider").on("click",playButtonSlider);
  function playButtonSlider() {
    function startTimer(counter) {
      if(counter <= 10) {
        setTimeout(function(){
          sliderValue = $("#slider").slider('value',2005+counter);
          counter += 0.1;
          startTimer(counter);
        },1);
      }
    }
    startTimer(0);
  }

  function renderMap(error, euRegionsJSON, sliderValue) {
    g.selectAll(".euMap").remove();
    g.selectAll("path")
        .data(euRegionsJSON.features)
        .enter().append("path")
        .attr("d", geoPath)
        .attr("class", "euMap")
        .attr("fill", function(d) {return color(d.properties[sliderValue]);})
        .style("stroke", "black")
        .style("stroke-width", "0.4px")
        .on("click",function(d) {
            highlight(this);
            setInfoBoxContent(d);
            createPlot(d);
        });
  }

  function highlight(mapClickedPath){
    d3.selectAll('path').style('fill',null);
    d3.select(mapClickedPath).style("fill", "#3333ff");
  }

  function setInfoBoxContent(mapClickedFeature) {
    $('#regionName').text(mapClickedFeature.properties.Region);
    $('#unemploymentRate').text(mapClickedFeature.properties[sliderValue]);
  }

  function zoomed() {
    g.style("stroke-width", 1.5 / d3.event.transform.k + "px");
    g.attr("transform", d3.event.transform);
  }

  $("#resetButton").on("click",reset);
  function reset(){
    svgEurope.transition().call(zoom.transform, d3.zoomIdentity);
    d3.selectAll('path').style('fill',null);
    $('#regionName').text("Europe");
    $('#unemploymentRate').text("100");
  }

  // Barplot
  var margin = {top: 10, right: 20, bottom: 35, left: 20};

  var svgPlotWidth = (0.33 * wrapperWidth) - margin.left - margin.right;
  var svgPlotHeight = 250 - margin.top - margin.bottom;

  var svgEuropeDiagramm = d3.select("#svgPlot").append("svg")
      .attr("width", svgPlotWidth + margin.left + margin.right)
      .attr("height", svgPlotHeight + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var x = d3.scaleBand()
            .rangeRound([0, svgPlotWidth])
            .padding(0.25);
  var y = d3.scaleLinear()
            .rangeRound([svgPlotHeight, 0]);

  function createPlot(mapClickedFeature) {

    var getFeatureEntries = d3.entries(mapClickedFeature.properties)
    var featureEntries = [];

    for (var i=0;i<=10;i++){
      if (getFeatureEntries[i].value == "NA") {
        getFeatureEntries[i].value = 0;
        featureEntries.push(getFeatureEntries[i])
      } else {
        featureEntries.push(getFeatureEntries[i])
      }
    }

    x.domain(featureEntries.map(function(d) { return d.key; }));
    y.domain([0, 50]);

    svgEuropeDiagramm.selectAll(".euPlot").remove();
    svgEuropeDiagramm.selectAll(".euPlot")
        .data(featureEntries)
        .enter().append("rect")
        .attr("class", "euPlot")
        .attr("x", function(d) { return x(d.key); })
        .attr("width", x.bandwidth())
        .attr("y", function(d) { return y(d.value); })
        .attr("height", function(d) { return svgPlotHeight - y(d.value); });

    svgEuropeDiagramm.selectAll(".xAxis").remove();
    svgEuropeDiagramm.append("g")
        .attr("transform", "translate(0," + svgPlotHeight + ")")
        .attr("class","xAxis")
        .call(d3.axisBottom(x))
      .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(90)")
        .style("text-anchor", "start");

    svgEuropeDiagramm.selectAll(".yAxis").remove();
    svgEuropeDiagramm.append("g")
        .attr("class","yAxis")
        .call(d3.axisLeft(y));
  }

EDIT: I checked my code with the provided sample JSON. I noticed that the function playButtonSlider() is moving the slider-handle way to fast. The JSON I use for my project is significantly larger and the slider-handle is moving reasonable slower. So something is definitely not coded well with the function playButtonSlider(). But I don't know a different approach to get the same effect.

sample JSON

      // Slider
  $("#slider").slider({
          value: 2005,
          min: 2005,
          max: 2015,
          step: 0.01,
          create: function(event, ui) {
              setSliderTicks(event.target);
          },
      })
      .each(function() {
          var opt = $(this).data().uiSlider.options;
          var vals = opt.max - opt.min;
          for (var i = 0; i <= vals; i++) {
              var el = $('<label>' + (i + opt.min) + '</label>').css('left', (i / vals * 100) + '%');
              $("#slider").append(el);
          }
      });

  function setSliderTicks(el) {
      var $slider = $(el);
      var max = $slider.slider("option", "max");
      var min = $slider.slider("option", "min");
      var spacing = 100 / (max - min);

      $slider.find('.ui-slider-tick-mark').remove();
      for (var i = 1; i < max - min; i++) {
          $('<span class="ui-slider-tick-mark"></span>').css('left', (spacing * i) + '%').appendTo($slider);
      }
  }
  // Responsive Design
  var windowWidth = window.innerWidth;
  var windowHeight = window.innerHeight;

  var wrapperWidth = 0.9 * windowWidth;
  var wrapperHeight;

  if (windowWidth < windowHeight) {
    wrapperHeight = 0.5 * windowHeight;
  } else {
    wrapperHeight = 0.75 * windowHeight;
  }

  $(".wrapper").css("width", wrapperWidth);
  $(".wrapper").css("height", wrapperHeight);

  // Map EU
  var svgMapWidth =  (0.65 * wrapperWidth)  - 4;
  var svgMapHeight = wrapperHeight - 4;

  var myProjection = d3.geoMercator()
      .center([8.00, 57.00])
      .scale(500)
      .translate([svgMapWidth / 2, svgMapHeight / 2]);

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

  var color = d3.scaleThreshold()
      .domain([0, 2, 4, 6, 8, 10, 15, 20, 25, 50])
      .range(["#006837", "#1a9850", "#66bd63", "#a6d96a", "#d9ef8b", "#fee08b", "#fdae61", "#f46d43", "#d73027", "#a50026", "#808080"]);

  var svgEurope = d3.select("#svgMap").append("svg")
      .attr("width", svgMapWidth)
      .attr("height", svgMapHeight);

  var g = svgEurope.append("g");

  var zoom = d3.zoom()
      .scaleExtent([0.25, 8])
      .on("zoom", zoomed);

  svgEurope.call(zoom);

  d3.queue()
    .defer(d3.json, "data/sampleData.json")
    .await(initializeData);

  function initializeData(error, euRegionsJSON) {
    if (error) throw error;
    $('#slider').slider().bind('slidechange',e => renderMap(e,euRegionsJSON, sliderValue)); //same as $('#slider').slider().bind('slidechange',function e() {return renderMap(e,euRegionsJSON, sliderValue)});
    $('#slider').trigger('slidechange');
  };

  var sliderValue;

  $('#slider').slider().bind('slidechange', function(event, ui) {
      sliderValue = $('#slider').slider("value");
      sliderValue = Math.floor(sliderValue);
      $("#currentYear").text(sliderValue);
  });

  $("#playButtonSlider").on("click",playButtonSlider);
  function playButtonSlider() {
    function startTimer(counter) {
      if(counter <= 10) {
        setTimeout(function(){
          sliderValue = $("#slider").slider('value',2005+counter);
          counter += 0.01;
          startTimer(counter);
        },10);
      }
    }
    startTimer(0);
  }

  function renderMap(error, euRegionsJSON, sliderValue) {
    g.selectAll(".euMap").remove();
    g.selectAll("path")
        .data(euRegionsJSON.features)
        .enter().append("path")
        .attr("d", geoPath)
        .attr("class", "euMap")
        .attr("fill", function(d) {return color(d.properties[sliderValue]);})
        .style("stroke", "black")
        .style("stroke-width", "0.4px")
        .on("click",function(d) {
            highlight(this);
            setInfoBoxContent(d);
            createPlot(d);
        });
  }

  function highlight(mapClickedPath){
    d3.selectAll('path').style('fill',null);
    d3.select(mapClickedPath).style("fill", "#3333ff");
  }

  function setInfoBoxContent(mapClickedFeature) {
    $('#regionName').text(mapClickedFeature.properties.Region);
    $('#unemploymentRate').text(mapClickedFeature.properties[sliderValue]);
  }

  function zoomed() {
    g.style("stroke-width", 1.5 / d3.event.transform.k + "px");
    g.attr("transform", d3.event.transform);
  }

  $("#resetButton").on("click",reset);
  function reset(){
    svgEurope.transition().call(zoom.transform, d3.zoomIdentity);
    d3.selectAll('path').style('fill',null);
    $('#regionName').text("Europe");
    $('#unemploymentRate').text("100");
  }

  // Barplot
  var margin = {top: 10, right: 20, bottom: 35, left: 20};

  var svgPlotWidth = (0.33 * wrapperWidth) - margin.left - margin.right;
  var svgPlotHeight = 250 - margin.top - margin.bottom;

  var svgEuropeDiagramm = d3.select("#svgPlot").append("svg")
      .attr("width", svgPlotWidth + margin.left + margin.right)
      .attr("height", svgPlotHeight + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  var x = d3.scaleBand()
            .rangeRound([0, svgPlotWidth])
            .padding(0.25);
  var y = d3.scaleLinear()
            .rangeRound([svgPlotHeight, 0]);

  function createPlot(mapClickedFeature) {

    var getFeatureEntries = d3.entries(mapClickedFeature.properties)
    var featureEntries = [];

    for (var i=0;i<=10;i++){
      if (getFeatureEntries[i].value == "NA") {
        getFeatureEntries[i].value = 0;
        featureEntries.push(getFeatureEntries[i])
      } else {
        featureEntries.push(getFeatureEntries[i])
      }
    }

    x.domain(featureEntries.map(function(d) { return d.key; }));
    y.domain([0, 50]);

    svgEuropeDiagramm.selectAll(".euPlot").remove();
    svgEuropeDiagramm.selectAll(".euPlot")
        .data(featureEntries)
        .enter().append("rect")
        .attr("class", "euPlot")
        .attr("x", function(d) { return x(d.key); })
        .attr("width", x.bandwidth())
        .attr("y", function(d) { return y(d.value); })
        .attr("height", function(d) { return svgPlotHeight - y(d.value); });

    svgEuropeDiagramm.selectAll(".xAxis").remove();
    svgEuropeDiagramm.append("g")
        .attr("transform", "translate(0," + svgPlotHeight + ")")
        .attr("class","xAxis")
        .call(d3.axisBottom(x))
      .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(90)")
        .style("text-anchor", "start");

    svgEuropeDiagramm.selectAll(".yAxis").remove();
    svgEuropeDiagramm.append("g")
        .attr("class","yAxis")
        .call(d3.axisLeft(y));
  }
deleted 1 character in body
Source Link
obrob
  • 151
  • 3

I created an interactive web map with d3. I am fairly new to web programming and am interested what you think about the code. The map is based on unemployment rates for each NUTS-2 regeionregion in europe. I created a sample JSON, so you maybe can use this for a working reproducible example. I hope the code provided is not too much.

I created an interactive web map with d3. I am fairly new to web programming and am interested what you think about the code. The map is based on unemployment rates for each NUTS-2 regeion in europe. I created a sample JSON, so you maybe can use this for a working reproducible example. I hope the code provided is not too much.

I created an interactive web map with d3. I am fairly new to web programming and am interested what you think about the code. The map is based on unemployment rates for each NUTS-2 region in europe. I created a sample JSON, so you maybe can use this for a working reproducible example. I hope the code provided is not too much.

deleted 48 characters in body
Source Link
obrob
  • 151
  • 3
Loading
Source Link
obrob
  • 151
  • 3
Loading