Created
November 15, 2019 13:25
-
-
Save justindenick/cdc737e40ece79d0928439b7c575ff7b to your computer and use it in GitHub Desktop.
google map geocode
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 | |
namespace App\Model\Behavior; | |
use ArrayObject; | |
use Cake\Event\Event; | |
use Cake\Http\Client; | |
use Cake\ORM\Behavior; | |
use Cake\ORM\Entity; | |
use Cake\ORM\Query; | |
use Cake\ORM\Table; | |
use Cake\ORM\TableRegistry; | |
/** | |
* GoogleMaps behavior | |
*/ | |
class GoogleMapsBehavior extends Behavior | |
{ | |
/** | |
* Default configuration. | |
* | |
* @var array | |
*/ | |
protected $_defaultConfig = []; | |
/** | |
* construct me | |
* | |
* @param Table $table the address table | |
* @param array $config the config | |
* @return void | |
*/ | |
public function __construct(Table $table, array $config = []) | |
{ | |
parent::__construct($table, $config + $this->_defaultConfig); | |
} | |
/** | |
* @param \Cake\Event\Event $event The beforeSave event that was fired | |
* @param \Geo\Model\Entity\Address $entity The entity that is going to be saved | |
* @param \ArrayObject $options the options passed to the save method | |
* @return void | |
*/ | |
public function beforeSave(Event $event, Entity $entity, ArrayObject $options) | |
{ | |
if (!$this->geocode($entity)) { | |
$event->stopPropagation(); | |
} | |
} | |
/** | |
* geocode | |
* i just want something simple | |
* | |
* @param Entity $entity the address entity | |
* @return bool | |
*/ | |
public function geocode(Entity $entity) | |
{ | |
$req = new Client(); | |
$res = $req->get( | |
'https://maps.googleapis.com/maps/api/geocode/json', | |
[ | |
'address' => $entity->address, | |
'key' => env('GOOGLE_MAPS_API_KEY') | |
], | |
['type' => 'json'] | |
); | |
if ($res->isOk()) { | |
$body = $res->getJson(); | |
$entity->set([ | |
'results' => json_encode($body['results']), | |
'formatted_address' => $body['results'][0]['formatted_address'], | |
'lat' => $body['results'][0]['geometry']['location']['lat'], | |
'lng' => $body['results'][0]['geometry']['location']['lng'], | |
]); | |
return true; | |
} | |
return false; | |
} | |
/** | |
* Formatted Address | |
* | |
* @param array $results gmapgeo body | |
* | |
* @return string | |
*/ | |
public function formattedAddress(Array $results) | |
{ | |
return $results['results'][0]['formatted_address']; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment