Skip to content

Commit

Permalink
Location onBeforeWrite
Browse files Browse the repository at this point in the history
  • Loading branch information
jsirish committed Dec 17, 2016
1 parent d20c7a1 commit e8e0555
Showing 1 changed file with 39 additions and 5 deletions.
44 changes: 39 additions & 5 deletions code/objects/Location.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,18 +304,52 @@ 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;
}

/**
*
*/
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();
}
}
}
}

0 comments on commit e8e0555

Please sign in to comment.