Last active
January 3, 2016 11:49
-
-
Save dfurber/8458390 to your computer and use it in GitHub Desktop.
Radius Search in Yii. Include WhereBehavior and RadiusSearchBehavior in your model in order to search byPointRadius or insideBounds.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class RadiusSearchBehavior extends CActiveRecordBehavior | |
{ | |
public function byPointRadius($lat, $lng, $radius) | |
{ | |
$radius = (float)$radius; | |
$distance = "((ACOS(SIN(:lat * PI() / 180) * SIN(lat * PI() / 180) + COS(:lat * PI() / 180) * COS(lat * PI() / 180) * COS((:lng - lng) * PI() / 180)) * 180 / PI()) * 60 * 1.1515)"; | |
$condition = "lat BETWEEN " . ($lat - $radius / 69.2) . " AND " . ($lat + $radius / 69.2) . " AND lng BETWEEN " . ($lng - $radius / 69.2) . " AND " . ($lng + $radius / 69.2) . " AND $distance<=:radius"; | |
return $this->owner->where($condition, array('lat' => $lat, 'lng' => $lng, 'radius' => $radius)); | |
} | |
public function insideBounds($nex, $ney, $swx, $swy) | |
{ | |
return $this->owner->where('lat<=:nex AND lat>=:swx AND lng<=:ney AND lng>=:swy', array('nex' => $nex, 'ney' => $ney, 'swx' => $swx, 'swy' => $swy)); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class WhereBehavior extends CActiveRecordBehavior | |
{ | |
/** | |
* Examples: | |
* User::model()->where("user_id=5"); | |
* User::model()->where("user_id", 5); | |
* User::model()->where("user_id", ">", 5); | |
* User::model()->where("first_name=:token OR last_name=:token", array('token' => "Furber")); | |
* @param mixed $col | |
* @param mixed $op | |
* @param mixed $val | |
*/ | |
public function where($col, $op = null, $val = null) | |
{ | |
if (!$op && !$val) | |
$this->owner->getDbCriteria()->addCondition($col); | |
else if ($op && !$val) | |
if (is_array($op)) | |
$this->owner->getDbCriteria()->mergeWith(array( | |
'condition' => $col, | |
'params' => $op, | |
)); | |
else | |
$this->owner->getDbCriteria()->compare($col, $op); | |
else | |
$this->owner->getDbCriteria()->compare($col, $op . $val); | |
return $this->owner; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment