diff --git a/controllers/ApiController.php b/controllers/ApiController.php index b9c0a32..f0a1d9f 100644 --- a/controllers/ApiController.php +++ b/controllers/ApiController.php @@ -48,7 +48,12 @@ class ApiController extends Controller { $minEditDate = isset($data['time']) ? intval($data['time']) : 0; - $points = Point::model()->getAllPublished(false, $minEditDate); + if ($minEditDate == 0) { + $points = Point::model()->getSortedByDistance(App::$userGeo['lat'], App::$userGeo['lng']); + } else { + $points = Point::model()->getAllPublished(false, $minEditDate); + } + $categories = Category::model()->getAll(array('order' => 'ord ASC', 'asArray' => true)); $result = array(); diff --git a/models/Point.php b/models/Point.php index 346d198..54f038b 100644 --- a/models/Point.php +++ b/models/Point.php @@ -86,6 +86,31 @@ class Point extends Model return $ready; } + public function getSortedByDistance($lat, $lng) + { + $lat = floatval($lat); + $lng = floatval($lng); + + $query = ' + SELECT *, ( + (POW(`lat`-:lat,2)+POW(`lng`-:lng,2)) + ) AS `dist` FROM `' . $this->_tableName_ . '` + WHERE + `status` = "published" + ORDER BY `dist`;'; + + $res = App::DB()->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); + $res->execute(array(':lat' => $lat, ':lng' => $lng)); + + $ready = array(); + $calledClass = get_called_class(); + while ($res && $row = $res->fetch(PDO::FETCH_ASSOC)) { + $ready[] = new $calledClass($row); + } + + return $ready; + } + public function getCountByUser($userId) { $res = App::DB()->query('SELECT count(`id`) AS `cnt` FROM ' . $this->_tableName_ . ' WHERE `author` = ' . $userId . ' AND `status` = "published";')->fetch(PDO::FETCH_ASSOC);