
The distance between two points is commonly used on the web, visit any store locator and the distance to the nearest branches is displayed.
But how do you display the direction? The answer is to use some simple maths.
To remember the order of the points of the compass I recall from my school days using the following.
This gives us four points of the compass, North, East, South, and West but this would be a bit vague when a point is NE or NW, so let’s add these in.
North, North East, East, South East, South, South West, West and North West.
This gives us 8 in total.
We all know that there are 360° in a circle, divide that by 8 and we get 45°.
We want all points of the compass to be offset by 22.5° this will mean that everything within a range is a direction, for example everything between 22.5° and 67.5 would be NE.
We know the length of the Opposite and Adjacent so using Sohcatoa we know we need to use Tangent.
Tangent(angle) = Opposite / Adjacent
We are going to write a function called direction which takes two sets of X and Y values as an argument.
To get the two sides of the triangle we will need to subtract the X and Y values from each other.
We can use TAN to calculate the angle of the triangle but luckily PHP has a function to calculate the arc tangent called ATAN2() which will save us a lot of work.
This line is where all the magic happens “$angle = atan2($difx, $dify) * 180 /M_PI;”
To make the angle relate to our compass angles we will need divide 180 degrees with pi (the PHP mathematical constant is M_PI) this multiplied with atan2() will give a bearing between 180° and +180°.
Keywords: Cosine, calculate direction, two points, 2 points, PHPLatest Posts 
17/11/15 
How to Create a Time Sheet in Excel 
15/11/15 
Handling time and dates in PHP 
03/02/15 
How to Enhance Photographs with the Gimp 
25/01/15 
How to Cook Pigeon 
25/01/15 
Telling the Time 
24/01/15 
An Old Travel Card 
10/09/14 
How to Learn the Nine Times Table 
09/08/14 
How to Calculate the Direction between two Points 
01/08/14 
Making a large Google XML sitemap 
18/05/14 
How to make a pyramid 