Languages
[Edit]
EN

JavaScript - calculate distance between two points with Pythagorean equation

17 points
Created by:
Aston-Freeman
787

In this article, we would like to show you how to calculate the distance between two points with the Pythagorean equation using JavaScript.

Quick solution:

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

Quick example:

// ONLINE-RUNNER:browser;

var a = 3 - 1;
var b = 3 - 1;
var distance = Math.sqrt(a * a + b * b);

console.log(distance); // 2.8284271247461903

 

1. Mathematical theorem on the coordinate system

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

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

a = |x2 - x1|

b = |y2 - y1|

c = sqrt(|x2 - x1|^2 + |y2 - y1|^2)

what can be transformed to:

c = sqrt((x2 - x1)^2 + (y2 - y1)^2)

distance beetween P1 and P2 is equal to c

Note: absolute value of a and b can be avoided because of squares inside Pythagorean equation - squares remove minuses.

Pythagorean equation in JavaScript.
The Pythagorean equation in JavaScript.

Example calculations:

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

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

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

2. JavaScript custom distance function example

// ONLINE-RUNNER:browser;

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

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

// Example:

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

var distance = calculateDistance(p1, p2);

console.log(distance);

3. 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;

    return Math.hypot(a, b);
}

// Example:

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

var distance = calculateDistance(p1, p2);

console.log(distance);

See also

  1. JavaScript - how to calculate distance between two points in 3D space?
  2. JavaScript - Chebyshev Distance function

  3. JavaScript - Rectilinear Distance function

References

  1. Pythagorean equation
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join