From e8e0555bf84a8780803ab69b03fab6f82a13ceea Mon Sep 17 00:00:00 2001 From: Jason Irish Date: Fri, 16 Dec 2016 21:14:34 -0600 Subject: [PATCH] Location onBeforeWrite --- code/objects/Location.php | 44 ++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/code/objects/Location.php b/code/objects/Location.php index 94b4bb0..640fa14 100644 --- a/code/objects/Location.php +++ b/code/objects/Location.php @@ -304,6 +304,34 @@ public function getCountryName() { return \Zend_Locale::getTranslation($this->Country, 'territory', i18n::get_locale()); } + /** + * @return bool + */ + public function hasAddress() { + return ( + $this->Address + && $this->City + && $this->State + && $this->PostalCode + && $this->Country + ); + } + + /** + * Returns TRUE if any of the address fields have changed. + * + * @param int $level + * @return bool + */ + public function isAddressChanged($level = 1) { + $fields = array('Address', 'City', 'State', 'PostalCode', 'Country'); + $changed = $this->owner->getChangedFields(false, $level); + foreach ($fields as $field) { + if (array_key_exists($field, $changed)) return true; + } + return false; + } + /** * */ @@ -311,11 +339,17 @@ public function onBeforeWrite() { parent::onBeforeWrite(); - if ($address = $this->getFullAddress()) { - $geocoder = new GoogleGeocoder($address); - $response = $geocoder->getResult(); - $this->Lat = $response->getLatitude(); - $this->Lng = $response->getLongitude(); + if ($this->hasAddress()) { + if (!$this->isAddressChanged()) { + return; + } + + if ($address = $this->getFullAddress()) { + $geocoder = new GoogleGeocoder($address); + $response = $geocoder->getResult(); + $this->Lat = $response->getLatitude(); + $this->Lng = $response->getLongitude(); + } } } }