Calculate distances and sort them

Posted by Emir on Stack Overflow See other posts from Stack Overflow or by Emir
Published on 2011-01-31T07:14:59Z Indexed on 2011/01/31 7:25 UTC
Read the original article Hit count: 207

Filed under:
|

Hi guys,

I wrote a function that can calculate the distance between two addresses using the Google Maps API.

The addresses are obtained from the database. What I want to do is calculate the distance using the function I wrote and sort the places according to the distance. Just like "Locate Store Near You" feature in online stores.

I'm going to specify what I want to do with an example:

So, lets say we have 10 addresses in database. And we have a variable $currentlocation. And I have a function called calcdist(), so that I can calculate the distances between 10 addresses and $currentlocation, and sort them. Here is how I do it:

$query = mysql_query("SELECT name, address FROM table");
while ($write = mysql_fetch_array($query)) {
    $distance = array(calcdist($currentlocation, $write["address"]));
    sort($distance);
    for ($i=0; $i<1; $i++) {
        echo "<tr><td><strong>".$distance[$i]." kms</strong></td><td>".$write['name']."</td></tr>";
    }
}

But this doesn't work very well. It doesn't sort the numbers.

Another challenge: How can I do this in an efficient way? Imagine there are infinite numbers of addresses; how can I sort these addresses and page them?

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql