Plotting Name of States on Map using Node js and D3 in real time

前端 未结 1 899
醉酒成梦
醉酒成梦 2021-01-21 03:52

I have been trying to plot the names of the states on the map using Redis Pub/Sub system, Node js and D3. Issue is that when I type in a state for first time on a Redis channel,

相关标签:
1条回答
  • 2021-01-21 04:13

    Create a variable for the texts and move it outside socket:

    d3.json("india-states.json", function (json) {
    india.selectAll("path")
      .data(json.features)
      .enter().append("path")
      .attr("d", path);
    
    var stateText = india.selectAll(".text")
      .data(json.features)
      .enter()
      .append("text");//variable outside socket
    
    var socket = io();
    
    socket.on('tags', function(data){
    
        stateText.attr("fill", "black")
          .attr("transform", function(d) {
            console.log(data.message1 + "Second Time"); 
            var centroid = path.centroid(d);
            return "translate(" + centroid[0] + "," + centroid[1] + ")"
          })
          .attr("text-anchor", "middle")
          .attr("dy", ".35em")
          .style('fill', 'white')
          .text(function(d) {
            if (d.id == data.message1) {   
                return data.message1;
              }
          });
      });
    });
    

    If you want to keep track of your previous message1, you can create an array outside the function, and loop through it:

    d3.json("india-states.json", function (json) {
    india.selectAll("path")
      .data(json.features)
      .enter().append("path")
      .attr("d", path);
    
    var stateText = india.selectAll(".text")
      .data(json.features)
      .enter()
      .append("text");
    
    var arrayStates = [];//this array will hold all the names
    
    var socket = io();
    
    socket.on('tags', function(data){
    
        arrayStates.push(data.message1);//for each input, a new string
    
        stateText.attr("fill", "black")
        .attr("transform", function(d) {
            var centroid = path.centroid(d);
            return "translate(" + centroid[0] + "," + centroid[1] + ")"
        })
        .attr("text-anchor", "middle")
        .attr("dy", ".35em")
        .style('fill', 'white')
        .text(function(d) {
            for(var i = 0; i < arrayStates.length; i++){
              if (d.id == arrayStates[i]) {   
                return arrayStates[i];
              }
            }
         });
      });
    });
    
    0 讨论(0)
提交回复
热议问题