Hey, I got some list of cities which includes Latitude & Longitude of every city. I got some point with Latitude & Longitude. I need to find closest cities to my point.
Find a way to include the haversine formula. Found HERE: # Where: # $l1 ==> latitude1 # $o1 ==> longitude1 # $l2 ==> latitude2 # $o2 ==> longitude2 function haversine ($l1, $o1, $l2, $o2) { $l1 = deg2rad ($l1); $sinl1 = sin ($l1); $l2 = deg2rad ($l2); $o1 = deg2rad ($o1); $o2 = deg2rad ($o2); return (7926 - 26 * $sinl1) * asin (min (1, 0.707106781186548 * sqrt ((1 - (sin ($l2) * $sinl1) - cos ($l1) * cos ($l2) * cos ($o2 - $o1))))); } PHP:
It returns the distance from any given point to any other given point. # Where: # $l1 ==> latitude1 # $o1 ==> longitude1 # $l2 ==> latitude2 # $o2 ==> longitude2 function haversine ($l1, $o1, $l2, $o2) { $l1 = deg2rad ($l1); $sinl1 = sin ($l1); $l2 = deg2rad ($l2); $o1 = deg2rad ($o1); $o2 = deg2rad ($o2); return (7926 - 26 * $sinl1) * asin (min (1, 0.707106781186548 * sqrt ((1 - (sin ($l2) * $sinl1) - cos ($l1) * cos ($l2) * cos ($o2 - $o1))))); } $point_lat = ""; //insert value here $point_lon = ""; //insert value here $query = mysql_query("SELECT * FROM `city_db`"); while ($row = mysql_fetch_object($query)) { $dist_array[haversine($row->lat, $row->lon, $point_lat, $point_lon)] = $row->city_name; // writes the distances into an array } ksort($dist_array); //orders the array foreach ($dist_array as $key => $val) { echo "$val = $key<br>"; } Code (markup): This should return all the the citys, starting with the city that is closest to your point. I haven't tested the script because I don't have such a database. Remember that you have to insert your values and sql field names.
In this example it is outputting information from an array. $row is an array $row->lat is the lattitude $row->lon is the longitude
that number at the end, is that KM ? because if its KM, its doesnt match the real distance between point and city. but look real in a sorting way.