Last active
December 20, 2015 18:09
-
-
Save csrui/6173911 to your computer and use it in GitHub Desktop.
CakePHP - Lib to handle spatial data
This file contains 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 | |
/** | |
* GeoBehavior handles a set of operations generaly needed when working with coordinates | |
* | |
* @source https://gist.github.com/csrui/6173911 | |
* @url http://book.cakephp.org/2.0/en/Models/behaviors.html | |
**/ | |
class GeoBehavior extends ModelBehavior { | |
public $settings = array(); | |
public function setup(Model $Model, $settings = array()) { | |
if (!isset($this->settings[$Model->alias])) { | |
$this->settings[$Model->alias] = array( | |
'field' => 'geo', | |
); | |
} | |
$this->settings[$Model->alias] = array_merge( | |
$this->settings[$Model->alias], (array)$settings); | |
} | |
/** | |
* Adds two virtual fields to model with Latitude and Logintude | |
* | |
**/ | |
public function beforeFind(Model $Model, $query) { | |
$Model->virtualFields = array( | |
'lat' => sprintf('x(%s.%s)', $Model->alias, $this->settings[$Model->alias]['field']), | |
'lng' => sprintf('y(%s.%s)', $Model->alias, $this->settings[$Model->alias]['field']) | |
); | |
return parent::beforeFind($Model, $query); | |
} | |
/** | |
* Handles conversion of virtual lat and lng fields into spatial data field | |
* | |
**/ | |
public function beforeSave(Model $Model) { | |
parent::beforeSave($Model); | |
if (!empty($Model->data[$Model->alias]['lat']) && !empty($Model->data[$Model->alias]['lng'])) { | |
$Model->data[$Model->alias][$this->settings[$Model->alias]['field']] = DboSource::expression(sprintf('POINT(%s, %s)', $Model->data[$Model->alias]['lat'], $Model->data[$Model->alias]['lng'])); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment