Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1574
暖寄归人
暖寄归人 2020-11-27 09:27

Given a set of latitude and longitude points, how can I calculate the latitude and longitude of the center point of that set (aka a point that would center a view on all poi

21条回答
  •  日久生厌
    2020-11-27 09:49

    Out of object in PHP. Given array of coordinate pairs, returns center.

    /**
     * Calculate center of given coordinates
     * @param  array    $coordinates    Each array of coordinate pairs
     * @return array                    Center of coordinates
     */
    function getCoordsCenter($coordinates) {    
        $lats = $lons = array();
        foreach ($coordinates as $key => $value) {
            array_push($lats, $value[0]);
            array_push($lons, $value[1]);
        }
        $minlat = min($lats);
        $maxlat = max($lats);
        $minlon = min($lons);
        $maxlon = max($lons);
        $lat = $maxlat - (($maxlat - $minlat) / 2);
        $lng = $maxlon - (($maxlon - $minlon) / 2);
        return array("lat" => $lat, "lon" => $lng);
    }
    

    Taken idea from #4

提交回复
热议问题