Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple trilateration algorithm implementation in JavaScript.
function getTrilateration(position1, position2, position3) {
var xa = position1.x;
var ya = position1.y;
var xb = position2.x;
var yb = position2.y;
var xc = position3.x;
var yc = position3.y;
var ra = position1.distance;
var rb = position2.distance;
var rc = position3.distance;
var S = (Math.pow(xc, 2.) - Math.pow(xb, 2.) + Math.pow(yc, 2.) - Math.pow(yb, 2.) + Math.pow(rb, 2.) - Math.pow(rc, 2.)) / 2.0;
var T = (Math.pow(xa, 2.) - Math.pow(xb, 2.) + Math.pow(ya, 2.) - Math.pow(yb, 2.) + Math.pow(rb, 2.) - Math.pow(ra, 2.)) / 2.0;
var y = ((T * (xb - xc)) - (S * (xb - xa))) / (((ya - yb) * (xb - xc)) - ((yc - yb) * (xb - xa)));
var x = ((y * (ya - yb)) - T) / (xb - xa);
return {
x: x,
y: y
};
}
@rfox90

This comment has been minimized.

Copy link

rfox90 commented Apr 22, 2014

What style of trilateration is this?

It seems to be suited for non earth based coordinates in perhaps virtual environments?

@ravisharma1987

This comment has been minimized.

Copy link

ravisharma1987 commented Oct 8, 2014

This is not working. I tested with point (0,0) (0,100) and (100, 0) and the answer it gave (NaN, 99.99645) for distances 107.70, 40.0 and 116.619 where as the point should be (40,100)

@Athanasius

This comment has been minimized.

Copy link

Athanasius commented Oct 10, 2014

The issue is that the code assumes that the 'a' and 'b' points don't have the same 'x' co-ordinate. It's the var x = line ending in '/ (xb - xa)'. They need to be different to avoid a divide by zero. Swap your 2nd and 3rd points and it'll work.

@pherris

This comment has been minimized.

Copy link

pherris commented Jan 19, 2015

Here is a link back to the author's youtube video with the use case: https://www.youtube.com/watch?v=dMWEl6GBGqk

@gheja

This comment has been minimized.

Copy link

gheja commented Jun 30, 2015

Just posted another trilateration, based on the Wikipedia derivation. I believe it is easier to follow it, also it is working in 3D space and returns [ 39.996, 99.996, +/-0.53 ] for your example input, @ravisharma1987 (can be configured to return the middle, then it returns [ 39.996, 99.996, 0 ]).
https://github.com/gheja/trilateration.js

@oDjonathanKrause

This comment has been minimized.

Copy link

oDjonathanKrause commented Oct 6, 2018

Hey guys!

I did an example using p5js.org

Thanks @kdzwinel for the help with the math!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.