patternphpMinor
Finding nearest city from a center place (latitude and longitude) with radius in miles
Viewed 0 times
withnearestplaceandmilesradiuscenterlatitudefindingcity
Problem
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.
";
}
$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 '';
for($ii=1;$ii=$minlat){
if($long[$ii]=$minlng)
echo ''.$rs[$n++] = $locat[$ii].'';
}
}
echo '';
?>Solution
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
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/(2piR)). For each city in the list apply the above formula. The city is "nearby" if the result is greater than cutoff.Context
StackExchange Code Review Q#49852, answer score: 2
Revisions (0)
No revisions yet.