I am trying to get value (says phone number) based on latitude and longitude in wordpress project. I have set of latitude longitude array like below,
$cities = Array(
"Abilene" => Array("number" => "(222) 333-1111", "lat" => 32.44874, "long" => -99.73314),
"Akron" => Array("number" => "(111) 111-0000", "lat" => 41.08144, "long" => -81.51901),
....
);
I got latitude and longitude using Geolocation plugin. Kindly look on the following code,
//returns nearest value
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest == null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
$latt_array = array();
$long_array = array();
foreach ($cities as $keys => $values) {
if (is_array($values)) {
foreach ($values as $k => $v) {
array_push($latt_array, $values['lat']);
array_push($long_array, $values['long']);
}
}
}
$match_city = array();
$latt = getClosest(49.8, $latt_array);
$long = getClosest(-71.032, $long_array);
foreach ($cities as $keys => $values) {
if (is_array($values)) {
if($values['lat'] == $latt ){
$values['city'] = $keys;
$match_city['lat'] = $values;
}
if($values['long'] == $long ){
$values['city'] = $keys;
$match_city['long'] = $values;
}
}
}
echo"<pre>"; print_r($match_city);echo"</pre>";
Above array returns matched latitute and longitude respectively like below.
Array
(
[long] => Array
(
[number] => (123) 123-1234
[lat] => 42.35843
[long] => -71.05977
[city] => Boston
)
[lat] => Array
(
[number] => (234) 123-2341
[lat] => 49.8844
[long] => -97.14704
[city] => Winnipeg
)
)
[long] => -71.05977 from long array , [lat] => 49.8844 from lat array will be my matched value here.
But my requirement is to match both latitude and longitude in $cities
array. Is there any other best way to get match latitude and longitude?. How can i match latitude and longitude in my array even in both positive and negative values ?
Kindly advice on this
You might want to calculate the actual distance between the location of the user and the location as set in the Array. Here is a great example how to do this in Javascript:
Calculate distance and bearing between to points in Javascript
You will have to rewrite this script for PHP. Than you can simply declare a distance variable and start looping through your array. Whenever the array distance is smaller than the distance declared in the distance variable you save the new distance in the distance variable and save the arrays key to a new variable. Example:
To code your own solution, use the haversine formula
Using the distance matrix built into google maps will help solve this problem on a much easier and scalable approach.