Find closest longitude and latitude in array?

后端 未结 4 1705
情深已故
情深已故 2020-12-12 23:04

I have a longitude and latitude as a string in PHP like below

49.648881
-103.575312

And I want to take that and look in an array of values

4条回答
  •  遥遥无期
    2020-12-12 23:22

    Iterate through the array, comparing values to what you have. If the value is smaller than your currently stored value (or if you don't have a currently stored value), store that value instead, otherwise throw it away.

    $closest = null;
    foreach($array as $key => $value){
        $distance = //compare distance here;
        if ($closest === null || $closest > $distance) {
            $closest = $distance;
        };
    };
    

    Of course, this will be made more difficult by the fact that latitude and longitude are on a sphere, and longitudes 179 and -179 are closer than 90 and 179.

提交回复
热议问题