Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Find Coordinates between two points

simple question here. Lets say I have two points:

point 1

x = 0
y = 0


point 2

x = 10
y = 10

How would i find out all the coordinates inbetween that programmatically, assuming there is a strait line between two points... so the above example would return:

0,0
1,1
2,2
3,3
...
8,8
9,9
10,10

Thanks :)

like image 843
Ozzy Avatar asked Dec 29 '22 23:12

Ozzy


2 Answers

You need to find the slope of the line first:

m = (y1 - y2) / (x1 - x2)

Then you need to find the equation of the line:

y = mx + b

In your example you we get:

y = 1x + b
0 = 1(0) + b

or

y = x

To get all of the coordinates you simply need to plug in all values x1 -> x2. In PHP this entire thing looks something like:

// These are in the form array(x_cord, y_cord)
$pt1 = array(0, 0);
$pt2 = array(10, 10);
$m = ($pt1[1] - $pt2[1]) / ($pt1[0] - $pt2[0]);
$b = $pt1[1] - $m * $pt1[0];

for ($i = $pt1[0]; $i <= $pt2[0]; $i++)
    $points[] = array($i, $m * $i + $b);

This will of course give you the coordinates for all points that fall on integer values of X, and not "all coordinates" between the two points.

like image 188
jasonbar Avatar answered Jan 10 '23 21:01

jasonbar


thanks for all your help but non of the answers posted worked how i wanted it to. For example, lets say my points were:

0, 0

0, 10

There would only be a start and a finish coordinate... it wouldnt find the ones inbetween.

Maybe i did something wrong :S but i came up with my own solution:

// Points
$p1 = array(
    'x' => 50,
    'y' => 50
);

$p2 = array(
    'x' => 234,
    'y' => 177
);

// Work out distances
$pxd = $p2['x'] - $p1['x'];
$pyd = $p2['y'] - $p1['y'];

// Find out steps
$steps = max($p1['x'], $p1['y'], $p2['x'], $p2['y']);

$coords = array();

for ($i = 0; $i < $steps; ++ $i) {
    $coords[] = array(
        'x' => round($p1['x'] += $pxd / $steps),
        'y' => round($p1['y'] += $pyd / $steps)
    );
}

print_r($coords);
like image 44
Ozzy Avatar answered Jan 10 '23 21:01

Ozzy