Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ‚̧ ūüíĽ
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

JavaScript - how to calculate distance between two points in 3D space?

0 contributions
2 points

Quick solution:

// P1 = (x1, y1, z1); P2 = (x2, y2, z2)
var a = x2 - x1;
var b = y2 - y1;
var c = z2 - z1;
var distance = Math.sqrt(a * a + b * b + c * c);

1. Overview

Distance calculation between two points is possible with midified Pythagorean equation. In this article, example how to calculate the distance is presented.

2. Mathematical theorem for coordinate system

Distance calculation for points requires to start with transformation of Pythagorean equation to point version.

a^2 + b^2 + c^2 = d^2 => d = sqrt(a^2 + b^2 + c^2)

P1 = (x1, y1, z1); P2 = (x2, y2, z2)

a = |x2 - x1|

b = |y2 - y1|

c = |z2 - z1|

d = sqrt(|x2 - x1|^2 + |y2 - y1|^2 + |z2 - z1|^2)

what can be transformed to:

d = sqrt((x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2)

distance beetwen P1 and P2 is equal to d

Note: absolute values can be avoided because of squares inside Pythagorean equation - squares remove minuses.

Example calculations:

P1 = (7, 2, 3); P2 = (3, 5, 8)

a = |x2 - x1| = |3 - 7| = 4

b = |y2 - y1| = |5 - 2| = 3

c = |z2 - z1| = |8 - 3| = 5

d = sqrt(4^2 + 3^2 + 5^2) = sqrt(16 + 9 + 25) = sqrt(50)

d = 7.071067811865475

3. JavaScript custom distance function example

// ONLINE-RUNNER:browser;

function calculateDistance(p1, p2) {
    var a = p2.x - p1.x;
    var b = p2.y - p1.y;
    var c = p2.z - p1.z;

    return Math.sqrt(a * a + b * b + c * c);
}

// Example:

var p1 = {x: 7, y: 2, z: 3};
var p2 = {x: 3, y: 5, z: 8};

var distance = calculateDistance(p1, p2);

console.log(distance);

4. Math.hypot method example

Note: Math.hypot has been introduced in ECMAScript 2015.

// ONLINE-RUNNER:browser;

function calculateDistance(p1, p2) {
    var a = p2.x - p1.x;
    var b = p2.y - p1.y;
    var c = p2.z - p1.z;

    return Math.hypot(a, b, c);
}

// Example:

var p1 = {x: 7, y: 2, z: 3};
var p2 = {x: 3, y: 5, z: 8};

var distance = calculateDistance(p1, p2);

console.log(distance);

See also

  1. JavaScript - how to calculate distance between two points with Pythagorean equation?
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey ūüĎč
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more