Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1577
暖寄归人
暖寄归人 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:56

    If you are interested in obtaining a very simplified 'center' of the points (for example, to simply center a map to the center of your gmaps polygon), then here's a basic approach that worked for me.

    public function center() {
        $minlat = false;
        $minlng = false;
        $maxlat = false;
        $maxlng = false;
        $data_array = json_decode($this->data, true);
        foreach ($data_array as $data_element) {
            $data_coords = explode(',',$data_element);
            if (isset($data_coords[1])) {
                if ($minlat === false) { $minlat = $data_coords[0]; } else { $minlat = ($data_coords[0] < $minlat) ? $data_coords[0] : $minlat; }
                if ($maxlat === false) { $maxlat = $data_coords[0]; } else { $maxlat = ($data_coords[0] > $maxlat) ? $data_coords[0] : $maxlat; }
                if ($minlng === false) { $minlng = $data_coords[1]; } else { $minlng = ($data_coords[1] < $minlng) ? $data_coords[1] : $minlng; }
                if ($maxlng === false) { $maxlng = $data_coords[1]; } else { $maxlng = ($data_coords[1] > $maxlng) ? $data_coords[1] : $maxlng; }
            }
        }
        $lat = $maxlat - (($maxlat - $minlat) / 2);
        $lng = $maxlng - (($maxlng - $minlng) / 2);
        return $lat.','.$lng;
    }
    

    This returns the middle lat/lng coordinate for the center of a polygon.

提交回复
热议问题