Vi implementerer det mere eller mindre som koden nedenfor (disclaimer:Jeg klippede dette ud af en fil og slettede koden, der var irrelevant for det aktuelle problem. Jeg kørte ikke dette, men du burde kunne få ideen.
$maxLat = $city->latitude + ($max_distance / 69); // 69 Miles/Degree
$minLat = $city->latitude - ($max_distance / 69);
$maxLon = $city->longitude + ($max_distance / (69.172 * cos($city->latitude * 0.0174533)));
$minLon = $city->longitude - ($max_distance / (69.172 * cos($city->latitude * 0.0174533)));
// Simplify terms to speed query
$originLatRadCos = cos($city->latitude * 0.0174533);
$originLatRadSin = sin($city->latitude * 0.0174533);
$originLonRad = $city->longitude * 0.0174533;
$city_distance_query = "
SELECT city_id,
3963 * acos(($originLatRadSin * sin( latitude * 0.0174533)) +
($originLatRadCos * cos(latitude * 0.0174533) * cos((longitude * 0.0174533) -
$originLonRad))) AS distanceFromOrigin
FROM cities
WHERE
latitude < $maxLat AND latitude > $minLat AND longitude < $maxLon AND longitude > $minLon";
Resten af forespørgslen
SELECT cities.city_name, CityDistance.distanceFromOrigin,
FROM cities
INNER JOIN ($city_distance_query) AS CityDistance ON CityDistance.city_id=cities.city_id
WHERE (distanceFromOrigin < $distance OR distanceFromOrigin IS NULL)