5
\$\begingroup\$

This is my code for finding the nearest city within a certain radius. I am not sure, is my code is OK or is it wrong? Please review and offer suggestions on my code.

<?
//Suppose,I have selected a city and fetch the selected city's lat and long and radius 
//in to this page.
$file_handle = fopen("Londonstations.csv", "r");
$i=0; $j=0; $k=0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$locat[$i++] = $line_of_text[0];
$lat[$j++] = $line_of_text[3];
$long[$k++] = $line_of_text[4];
//print $line_of_text[0]; . $line_of_text[1]. $line_of_text[2] . "<BR>";
}
$l = $_POST['l'];//This value is received from previous page selected places latitude and longitude index from array.
$r = $_POST['r'];//This value is received from previous page selected places for //finding city that are in located in this radius
$radius = 3958.761; //earth's radius in miles
 // we'll want everything within, say, distance
$distance = $r;//This value is received from previous page, radius of selected 
 //places for finding city that are in located in this radius

// latitude boundaries 
$maxlat = $lat[$l] + rad2deg($distance / $radius);
$minlat = $lat[$l] - rad2deg($distance / $radius);

// longitude boundaries (longitude gets smaller when latitude increases)
$maxlng = $long[$l] + rad2deg($distance / $radius / cos(deg2rad($long[$l])));
$minlng = $long[$l] - rad2deg($distance / $radius / cos(deg2rad($long[$l])));
$n=1;
echo 'Nearest Stations:';
echo '<ul>';
for($ii=1;$ii<$i;$ii++){
if($lat[$ii]<=$maxlat && $lat[$ii]>=$minlat){
    if($long[$ii]<=$maxlng && $long[$ii]>=$minlng)
        echo '<li style=style:circle>'.$rs[$n++] = $locat[$ii].'</li>';
} 
}
echo '</ul>';
?>
\$\endgroup\$
2
\$\begingroup\$

I din't check your math, because in any case the code doesn't do what it claims to do. The returned points are not within the given distance of the center, but belong to some square-like area.

To calculate a distance as the crow flies, notice that a cosine of the angular distance theta is

$$ \cos\theta = \cos\phi_0\cos\phi_1\cos(\psi_0 - \psi_1) + \sin\phi_0\sin\phi_1 $$

where Phi and Psi are respective latitudes and longitudes. The greater cosine, the closer points are.

Given a distance d, calculate cutoff = cos(d/(2*pi*R)). For each city in the list apply the above formula. The city is "nearby" if the result is greater than cutoff.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.