Experiencing difficulties when trying to pan and zoom the data obtained from d3.json within a line chart

I am currently working on developing a trend component that can zoom and pan into data fetched using d3.json. Here is the code I have written so far:

<script>

    var margin = { top: 20, right: 80, bottom: 20, left: 50 },
        width = $("#trendcontainer").width() - margin.left - margin.right,
        height = 500 - margin.top - margin.bottom;

    var format = d3.time.format("%Y-%m-%d").parse;
    var x = d3.time.scale()
        .domain([-width / 2, width / 2])
        .range([0, width]);

    var y = d3.scale.linear()
        .domain([-height / 2, height / 2])
        .range([height, 0]);
    
    // More code here...

</script>

The issue I'm facing is that when zooming or panning, my lines do not interact as expected. They remain static below the zoomable/pannable grid. In addition, one of the lines disappears while attempting to zoom/pan, and an error message appears in the console: Error: Problem parsing d="" - referencing the following snippet, specifically the last line:

function zoomed() {
    svg.select(".x.axis").call(xAxis);
    svg.select(".y.axis").call(yAxis);
    svg.select(".x.grid")
        .call(make_x_axis()
            .tickSize(-height, 0, 0)
            .tickFormat(""));
    svg.select(".y.grid")
        .call(make_y_axis()
            .tickSize(-width, 0, 0)
            .tickFormat(""));
    svg.select(".line")
        .attr("class", "line")
        .attr("d", line);
};

Here's a snippet of the JSON data retrieved from the controller:

[{"Weight":0.0,"Speed":59.9,"Depth":362.24000,"Time":"2014-04-09T10:01:23","Id":0},{"Weight":10.0,"Speed":59.9,"Depth":394.07000,"Time":"2014-04-09T10:01:56","Id":1},
// More data here...
]

Currently, the trend in my view does not allow for the actual lines to zoom or pan. Only the grid overlay (black lines) does;

In order to simplify things, I have considered starting over and following the original example provided here. However, I am finding it challenging to integrate JSON-loaded data into this structure. I hope someone can assist me in resolving these issues :)

Answer №1

Thanks to the help from Lars, I was able to successfully resolve this issue. I made adjustments to my controller and utilized this fiddle which helped with assigning scales to the zoom behavior after setting the domains. This resulted in returning a JSON string to my view like so:

string json = JsonConvert.SerializeObject(Model.Trend.ToArray());

return Json(json, JsonRequestBehavior.AllowGet);

The need for serialization arose when errors occurred during zooming/panning on the unserialized array returned to the view.

In addition to these changes, I also had to implement the following steps to ensure functionality:

d3.json('@Url.Action("DataBlob", "Trend", new {id = Model.Unit.UnitId, runId = 5})', function(error, tmparray) {
    var json = JSON.parse(tmparray);
    ...
    )};

Omitting these additional steps led to improper display of my data, causing it to be compressed to the left side of the graph.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Renaming errors within a project with a complex nested structure using npm

I am encountering an issue in my NodeJS project which consists of nested subprojects with their own package.json files. Whenever I make changes to dependencies in the subprojects, I encounter errors similar to the one below: npm ERR! code ENOENT npm ERR! ...

loop through nested arrays

My goal is to use ng repeat in Angular to iterate through a child array of a multidimensional array. The json object I am working with is as follows: $scope.items = [{ "id":1, "BasisA":"1", "Basis":true, "personSex": ...

Validate a JSON object key

There are two ways in which we receive JSON strings: "{"phoneNumber":[{"remove":["0099887769"]},{"add":["0099887765"]}]}" Or "{"phoneNumber":["0099887765"]}" We need to convert the JSON string from the first format to the second format. Is there a way ...

Issue with Angular Factory not being invoked

I am currently using a tutorial to create a MEAN app with Google Maps. However, I have encountered an issue where the map is not appearing on the page. Surprisingly, there are no errors in the browser console and even when debugging with node-inspector, I ...

Accessing specific elements within multi-dimensional arrays using JavaScript

I've embarked on the exciting journey of creating my own 'Choose Your Adventure!' game, but I've hit a snag. I'm struggling to effectively target specific values within the multi-dimensional array I constructed. In order to add som ...

Verify if the value of localStorage matches the specified value, then conceal the element

This is my second query and I'm hoping it covers everything. My knowledge of javascript is limited, which has made it difficult for me to get my code working properly. Despite trying various different approaches, I have been unable to resolve the issu ...

Making a JSON POST request from an Android device

As a beginner in Android development, I have learned that the method for sending post requests is deprecated in Android 22 and later versions. Can anyone provide a sample of working Android code using the URLCONNECTION method to send a JSON POST request ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...

Can you guide me on how to export a named function using module.exports?

I have a script file for my discord bot that includes a specific command and a function with parsing logic that I want to reuse in my main index.js // File: ./commands/scrumPrompt.js // The function const extractDeets = function (f, scrum) { let items ...

The resolve in Angular UI-Router is not being properly injected into the controller

As a Java developer venturing into the world of Angular and Express, I am encountering challenges along the way. To gain hands-on experience, I am attempting to create a small application using these technologies. The Goal: I have provided a password rese ...

Effective methods to avoid showcasing AdSense advertisements

For the purpose of creating a responsive design, I am attempting to hide an adsense ad unit on smaller screen sizes. Although I am familiar with the method of using css media queries as outlined on Google AdSense support page, I have encountered an error w ...

Can you explain the meaning of the code snippet provided?

<script type="text/javascript> window.onload = function(){ //execute some code here },function(){ // execute another piece of code here }(); </script> Is this code indicating that multiple function ...

Tips on maintaining and hiding the vertical scrollbar when a popup is open, alongside the navigation bar positioned at the top of the page

After reviewing this pen, my goal is to create a popup that maintains access to the navigation bar (hence avoiding Bootstrap's Modal). However, I am facing the challenge of keeping the scrollbar visible while preventing scrolling in the background whe ...

What do you prefer: defining properties with the JSON object or with objectName.property in JavaScript

Can you tell me which approach is considered the best practice? Is it better to use the "this" statement in the following way: var obj = { x: 20, y: 10, width: this.x, height: this.y, render: function () { // renders object on canvas ctx.fi ...

Show each individual layer from a KMZ file on a map with the ArcGIS API for JavaScript

Can I selectively show specific layers from a kmz file on my map? My current setup involves using the ArcGIS API for JavaScript. Specifically, I want to display only folders related to the current day outlook from a KMZ file provided by the NWS. There are ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

Is there a way to determine the model name programmatically within a Sails.js lifecycle callback?

Two models are present, with one model extending from the other. For all sub-models to inherit a lifecycle callback defined in BaseObject, I need a way to retrieve the name of the model being acted upon within the callback. This information is crucial for ...

Struggling with parsing intricate JSON data into an object with GSON?

Through a service API call, I am receiving a JSON String with data that includes various reportRecords. For simplicity, I have included only three of these records out of the potential ~500. Here's an excerpt of the JSON response: { "aggRecords": ...

Is there a way to execute v-for once the created() lifecycle hook has finished running?

In my current project, I am faced with the challenge of including avatars in notifications. Despite my efforts, I have not been able to solve this issue independently. The Vue.js template below demonstrates how I have attempted to add avatars to each notif ...

What could be causing VueJs2 computed properties to not update?

Check out this updated grid example from the official examples. In my application, I need to reposition the sortOrders array. created: function () { var vm = this; this.columns.forEach(function (key) { vm.sortOrders[key] = 1 }) ...