1

I have following array and according to my "Lat,Long" (dynamic) i want to get nearby locations from array,how can i do this ? Here is my lat long

$lat="30.741190";
$lng="76.806343";

Here is my array

<pre>Array
(
    [0] => Array
        (
            [CityName] => Jaunpur
            [distance] => 1.2316498252150263
            [latitude] => 30.741190
            [longitude] => 76.764381
            )

    [1] => Array
        (
            [CityName] => Def
            [distance] => 3.710097860029201
            [latitude] => 30.740700
            [longitude] => 76.806343
             )
)
  • 1
    If your array already contains the distance, what problem do you have in getting the details you want? – Nigel Ren Jun 05 '21 at 06:44

1 Answers1

1

I use a function :

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $theta = $lon1 - $lon2;
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
  $dist = acos($dist);
  $dist = rad2deg($dist);
  $miles = $dist * 60 * 1.1515;
  $unit = strtoupper($unit);

  if ($unit == "K") {
      return ($miles * 1.609344 );
  } else if ($unit == "N") {
      return ($miles * 0.8684);
  } else {
      return $miles;
  }
}

Now loop over array

$distances = array();
    foreach($arrayname as $ind => $entry){
    $dist=distance($entry["latitude"],$entry["longitude"],$lat,$lng,"K");
    echo $dist;
$distances[$entry["cityname"]]=round($dist);
    }

//now sort distances array in ascending:

$distances = sort($distances);
aryanknp
  • 1,135
  • 2
  • 8
  • 21