Page 1 of 1

Determining the distance between two points using a (x,y) coordinate system Rate Topic: -----

#1 rjolitz  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 3
  • View blog
  • Posts: 110
  • Joined: 17-May 08

Posted 03 August 2008 - 02:11 AM

Hello!

In this tutorial we are going to tackle a rather basic problem. How to determine the distance between two points on an X,Y grid.

Our starting points for the purpose of this tutorial will be (1,-10) and (15,-20). For our code we will be setting these values into variables but you can also accept them from a form as well as pull them from a MySQL database depending on your project.

First we'll set our variables and give them a value:


<?php

// first coordinate set (1,-10)
$x1 = 1;
$y1 = -10;

// second coordinate set (15,-20)
$x2 = 15;
$y2 = -20;




The next step is to subtract the x coordinate of the first set from the second set. We also need to do the same for the y coordinates. Then both values need to be squared. This is easily accomplished using PHP's pow(x,y) function. X equals the value to be raised, y equals the power to raise it by. If you want to know the value of 10 to the 9th power it would like pow(10,9)


$x = ( pow($x2,2) - pow($x1,2));
$y = ( pow($y2,2) - pow($y1,2));




The last step is to add these two values and find the square root.


$distance = ( sqrt($x + $y) );




For our example the final answer is 22.891046284519. If you want to round this value to nearest full number you can use the round() function, which will round the number up or down. If you want to round to a certain number of decimal places, you can specify that such as round(11,3)

round($distance) returns the value: 23

round($distance,2) returns the value: 22.89

Putting it all together our code looks like:


<?php

// first coordinate set (1,-10)
$x1 = 1;
$y1 = -10;

// second coordinate set (15,-20)
$x2 = 15;
$y2 = -20;

$x = ( pow($x2,2) - pow($x1,2));
$y = ( pow($y2,2) - pow($y1,2));

$distance = ( sqrt($x + $y) );

// Round to nearest full number

$roundtofull = round($distance);
$roundto2places = round($distance,2);


?>




This tutorial is really basic in showing how to determine distance, but I do hope you found it useful.

Is This A Good Question/Topic? 1
  • +

Replies To: Determining the distance between two points

#2 grokmygeek  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 1
  • Joined: 06-March 09

Posted 06 March 2009 - 10:04 AM

Your math is flawed. I wouldn't want you doing my homework for me.

$x = ( pow($x2,2) - pow($x1,2));
$y = ( pow($y2,2) - pow($y1,2));

$distance = ( sqrt($x + $y) );



Should read...

$x = ( pow($x2-$x1,2));
$y = ( pow($y2-$y1,2));

$distance = ( sqrt($x + $y) );


Was This Post Helpful? 1
  • +
  • -

#3 Guest_Guest*


Reputation:

Posted 29 March 2010 - 08:36 AM

I have to agree with the correction made by
grokmygeek, on 06 March 2009 - 09:04 AM
Was This Post Helpful? 1

Page 1 of 1