The d3.js Force Directed Graph is not working as expected

I keep encountering an error in the dev console whenever I attempt to run my code. The errors are as follows:

Error: missing: 1 3d-force-graph:5:22166
TypeError: r.attributes.position is undefine

You can view the live version of the faulty code here:

Here is the actual code snippet:

<!DOCTYPE html>
<meta charset="utf-8">
<head>
  <style> body { margin: 0; } </style>
   <script src="//unpkg.com/3d-force-graph"></script>
  <!--<script src="3d-force-graph.js"></script>-->
</head>

<body>
  <div id="3d-graph"></div>

  <script>
    const elem = document.getElementById('3d-graph');
    const Graph = ForceGraph3D()
      (elem)
    .graphData({"nodes":[{ "name": "Myriel","group":  1 },{ "name": "Napoleon","group":  1 }], links: [ { "source":  1,  "target":  2,  "value":  1 }]})
        .nodeLabel('id')
        .nodeAutoColorBy('group')
        .onNodeHover(node => elem.style.cursor = node ? 'pointer' : null)
     .onNodeClick(node => {
          // Aim at node from outside it
          const distance = 40;
          const distRatio = 1 + distance/Math.hypot(node.x, node.y, node.z);

          Graph.cameraPosition(
            { x: node.x * distRatio, y: node.y * distRatio, z: node.z * distRatio }, // new position
            node, // lookAt ({ x, y, z })
            3000  // ms transition duration
          );
        });
  </script>
</body>

This code is a modified version based on the following source code: https://github.com/vasturiano/3d-force-graph/blob/master/example/click-to-focus/index.html

The only change I made was replacing the jsonUrl method with static data input.

I have attempted debugging through the Dev Console but have been unable to resolve the issue.

Your assistance would be greatly appreciated.

Answer №1

Please add the "id" attribute

<!DOCTYPE html>
<meta charset="utf-8">
<head>
  <style> body { margin: 0; } </style>
   <script src="//unpkg.com/3d-force-graph"></script>
  <!--<script src="3d-force-graph.js"></script>-->
</head>

<body>
  <div id="3d-graph"></div>

  <script>
    const elem = document.getElementById('3d-graph');
    const Graph = ForceGraph3D()
      (elem)
    .graphData({"nodes":[{ "name": "Myriel","group":  1, "id" : 1},{ "name": "Napoleon","group":  1, "id": 2 }], links: [ { "source":  1,  "target":  2,  "value":  1 }]} )
        .nodeLabel('name')
        .nodeAutoColorBy('group')
        .onNodeHover(node => elem.style.cursor = node ? 'pointer' : null)
     .onNodeClick(node => {
          // Aim at node from outside it
          const distance = 40;
          const distRatio = 1 + distance/Math.hypot(node.x, node.y, node.z);

          Graph.cameraPosition(
            { x: node.x * distRatio, y: node.y * distRatio, z: node.z * distRatio }, // new position
            node, // lookAt ({ x, y, z })
            3000  // ms transition duration
          );
        });
  </script>
</body>

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

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Exploring the power of hierarchical organization in node.js modules

One of my modules is called UserProvider and it has the following structure: var UserProvider = function(db) { ... } UserProvider.prototype.createUser = function(email, password, callback) { ... } UserProvider.prototype.findUserByEmail = function(email, c ...

What methods can I use to identify if the browser my users are using does not have support for Bootstrap 4?

My recent project heavily utilizes the advanced features of Bootstrap 4/CSS, making it incompatible with older browsers still in use by some of my visitors. How can I effectively identify when a user's browser does not support bootstrap 4 so that I c ...

Executing a function from index.html that continuously loops without any limits

I'm currently working on creating a function that displays specific HTML content only to users with certain roles. Here are the functions I've set up for this: nodejs/server.js app.get('/api/isadmin', ensureAuthenticated, function (re ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

Different option for positioning elements in CSS besides using the float

I am currently working on developing a new application that involves serializing the topbar and sidebar and surrounding them with a form tag, while displaying the sidebar and results side by side. My initial attempt involved using flex layout, but I have ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

What can you do to ensure Vue detects input element changes after using preventDefault?

In this example, I am trying to prevent a newline from being created in a textarea when the Enter key is pressed. To achieve this, I use the preventDefault method in my event handler and update the value inside the textarea. However, I encounter an issue w ...

NextJS middleware API receives an uploaded image file form, but the request is undefined

Currently, I'm utilizing NextJS to handle form data processing and database uploads, with a pit stop at the NextJS API middleware for image editing. pages/uploadImage.tsx This is the client-side code handler. ... async function handleImageUpload(imag ...

Angular failing to reflect changes in my select element according to the model

One issue I'm facing in my application is with grouped select elements that share the same options. Whenever one select element changes, it checks the others to see if the new option selected has already been chosen in any of the other selects. In suc ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...

Adding Node Modules during the setup of an ElectronJS application

Hey there! I'm currently working on an ElectronJS application designed for developers. One of the key features is checking for the presence of NodeJS on the user's computer. If it's not detected, the app will automatically download and insta ...

Exploring the depths of Master-Detail functionality with Ionic and Angular, unlocking nested

Hey there! I'm currently working on a project using Ionic and Angular, where users can view events and see all the attending participants along with their information. To achieve this, I implemented a master-detail pattern within another master-detail ...

Convert a web page with embedded images using Base64 strings into a PDF file using JavaScript

My website has numerous images with base 64 string sources. Typically, I am able to download the HTML page as a PDF using a service method that involves sending the HTML page with a JSON object and receiving the PDF in return. However, when there are many ...

"Discovering a button press using the Gamepad API: A Step-by-Step Guide

I'm currently building a web page that can detect button presses on an Xbox controller and display a boolean value based on the pressed button. Right now, I have successfully managed to detect when a controller is connected and show it as a string. Ho ...

Using JavaScript to analyze and handle newlines, spaces, and the backslash character

Hello everyone, I'm hoping things are going well. I am currently working on removing newline and "\" characters from a string that I have after using JSON.stringify(). The string in question appears as follows: "[{\n \"id_profile&bs ...

Explore the feature of toggling visibility of components in Vue.js 3

I am facing an issue with showing/hiding my sidebar using a button in the navbar component. I have a navbar and a side bar as two separate components. Unfortunately, none of the methods I tried such as v-show, v-if, or using a localStorage value seem to wo ...

Control and manage AJAX POST requests in the controller

I'm currently working on implementing an ajax post request feature in my project. The goal is to have a button on my html page trigger a javascript event listener, which then initiates an ajax post request to receive some text data. However, I seem to ...

`how to extract the href attribute value from the hyperlink that triggered a modal in jQuery UI`

Recently, I began diving into Jquery and javascript coding. As a beginner, it feels odd to refer to myself as a noob due to my age. Here's the scenario: I have a hyperlink that triggers a dialogue box and sets a cookie. The dialog asks the user, "Are ...

Error Uploading File - Functioning in Postman but not on website interface

I'm currently pursuing the full stack certification on devchallenges.io and tackling the authentication app challenge. So far, I've successfully implemented the login and register functionality, as well as fetching the logged-in user's infor ...