Bookmark and Share

20

Apr

2010

Although at first thought it might not seem it, it’s actually very simple to find the closest location in PHP or MySQL when given a range of of longitude and latitude coordinates.

First, lets look at the maths. For those in the know, we’re essentially calculating the difference in the hypotenuse. Whichever result returns the lowest number from our data set will be the closest.

The number we need is the Square Root (√) of:
(firstLongitude-secondLongitude)*(firstLongitude-secondLongitude)
+
(firstlLatitude-secondLatitude)*(firstLatitude-secondLatitude)

Obviously, this number is useless if we have only two locations (and then we wouldn’t be interested in which was the closest anyway!), so we would loop this equation, changing the second lat/long for each location, to figure which is nearest.

In PHP we can do that like this:

<?php
 
$value = sqrt((($firstLongitude-$secondLongitude)*($firstLongitude-$secondLongitude))+(($firstlLatitude-$secondLatitude)*($firstLatitude-$secondLatitude)));
 
?>

Remember, we’d need this to loop to be useful.

And in MySQL we’d select the data like this:

ORDER BY SQRT
(((fLongitude-sLongitude)*(fLongitude-sLongitude))
+((fLatitude-sLatitude)*(fLatitude-sLatitude))) 
ASC LIMIT 1;

Hopefully this will help you get the ground work in place to make a decent start.

Comments (3)

JohnnyArt said at 06:44 on 17th May 2010

You should use the function ‘pow’ provided by php like this:
$distance = sqrt(pow($f[1]-$s[1],2)+pow($f[2]-$s[2],2));

The format is the following:
pow(what,power);

Gavin Pearce said at 19:27 on 18th May 2010

Thanks Johnny! Nice tip.

John said at 08:00 on 14th July 2010

Thanks a lot for this. I’m programmer but not from a nonmath background and I was wondering about how I could tackle this issue!

 

Post a comment

Post comments to this article by filling in your details below.