Forum Moderators: coopster

Message Too Old, No Replies

How to find nearest coordinat in php

         

Heeren

6:25 am on Sep 21, 2006 (gmt 0)

10+ Year Member



hello
i want to find nearest cordinate of (x,y) in php
like (20,30) i want find the top 5 nearest cordinate to that , how i could this please tell me

adb64

6:43 am on Sep 21, 2006 (gmt 0)

10+ Year Member



Assuming that, next to (x,y), you also have other coordinates (xn,yn) then for each pair (xn,yn) you can use the following formula:

dn = (x - xn)2 + (y - yn)2

When you did that for all coordinate pairs (xn,yn), find the five smallest dn values.
It shouldn't be too complex to translate this into a PHP function.

Heeren

6:47 am on Sep 21, 2006 (gmt 0)

10+ Year Member



thanks for ur formula
but i should do with the database , how should i do with database .
i want to find top 5 nearest abt two cordinate(20,40)
i have two columne X and Y and i want to find nearest 5 record of that cordinate like exp
(19,39),(21,41),(19,41),(20,39)
how should i find throgh query
pls help me

[edited by: Heeren at 6:48 am (utc) on Sep. 21, 2006]

adb64

7:13 am on Sep 21, 2006 (gmt 0)

10+ Year Member



Try something like this:


/* some example values, fill in your own values */
$NumberOfCoordinatePairs = 10;
$x = 20;
$y = 40;
for ($i = 0; $i < $NumberOfCoordinatePairs; $i++)
{
[Some code to get the values from database row $i into $xn[$i] and $yn[$i], find that out yourself]
$d[$i] = pow($x - $xn[$i], 2) + pow($y - $yn[$i], 2);
}
$a[0] = $a[1] = $a[2] = $a[3] = $a[4] = 9999999999;
for ($i = 0; $i < $NumberOfCoordinatePairs; $i++)
{
for ($j = 0 ;$j < 5; $j++)
{
if ($d[$i] < $a[$j])
{
for ($k = 4; $k > $j; $k--)
{
$a[$k] = $a[$k-1];
}
$b[$j] = $i;
$a[$j] = $d[$i];
$j = 5;
}
}
}

Now you have an array $b of which each index contains the index into the $xn and $yn arrays of the five coordinates that are nearest to (x,y). When you have less than 5 coordinates to check against not all indexes of $b are set then.
I didn't test this code by the way.
Also it isn't optimised, the two loops can be combined for instance.