Skip to content

Instantly share code, notes, and snippets.

@tai-sho
Created July 11, 2017 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tai-sho/025659c259802630d3137944338c791c to your computer and use it in GitHub Desktop.
Save tai-sho/025659c259802630d3137944338c791c to your computer and use it in GitHub Desktop.
GoogleMapAPIのgeocodingAPI #cakephp
<?php
/**
* GoogleMapAPIコンポーネント
*/
class GoogleMapAPIComponent extends Component {
/**
* APIベースURL
* @var string
*/
public $baseUrl = 'https://maps.googleapis.com/maps/api/';
/**
* レスポンスの言語
* @var string
* @see https://developers.google.com/maps/faq?hl=ja#languagesupport
*/
public $language = 'ja';
/**
* APIキー
* @var array
*/
protected $_apiKey = array();
/**
* APIタイムアウト秒数
* @var integer
*/
const API_TIMEOUT = 60;
/**
* コンストラクタ
* @param ComponentCollection $collection コンポーネントコレクション
* @param array $settings コンポーネント設定
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct($collection, $settings);
App::uses('HttpSocket', 'Network/Http');
}
/**
* ジオコーディングAPI
* @param array $params パラメータ
* @return array
* @throws InternalErrorException
*/
public function geocoding(array $params) {
$params['language'] = isset($params['language']) ? $params['language'] : $this->language;
$params['key'] = $this->_apiKey['geocoding'];
$result = $this->_getRequest('geocode/json', $params);
if(!in_array($result['status'], array('OK', 'ZERO_RESULTS'), true)) {
throw new RuntimeException();
}
return $result['results'];
}
/**
* GET送信を行います。
* @param string $uri APIのURL
* @param array $data パラメータ
* @param array $header header
* @return array
*/
protected function _getRequest($uri, array $data, $header = array()) {
return $this->_request(array(
'method' => 'GET',
'header' => $header,
'uri' => $uri. Router::queryString($data)
));
}
/**
* リクエストを実行します。
* 通信成功した場合は配列を返します。
* 通信失敗やjsonデコードに失敗した場合は配列のstatusをfalseで返します。
* @param string $uri APIのURL
* @param array $params パラメータ
* @return array
* @throws InternalErrorException 通信に失敗した場合
*/
protected function _request(array $params = array()) {
$socket = new HttpSocket(array(
'timeout' => self::API_TIMEOUT
));
$params['uri'] = $this->baseUrl. $params['uri'];
// リクエスト実行
$response = $socket->request($params);
$result = json_decode($response['body'], true);
// jsonのデコードに失敗した場合
if(empty($result)){
throw new InternalErrorException();
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment