Created
July 28, 2014 23:08
-
-
Save lkacenja/58e28e760d9f848538a7 to your computer and use it in GitHub Desktop.
Class for using the google distance api
This file contains hidden or 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 | |
class omfGoogleDistanceMatrix { | |
protected $origins = array(); | |
protected $destinations = array(); | |
protected $unit = 'imperial'; | |
protected $mode = 'driving'; | |
protected $language = 'en'; | |
protected $api_key = ''; | |
protected $endpoint = 'https://maps.googleapis.com/maps/api/distancematrix/json'; | |
public function __construct($api_key = '') { | |
if (!empty($api_key)) { | |
$this->set_api_key($api_key); | |
} | |
} | |
public function set_api_key($api_key) { | |
$this->api_key = $api_key; | |
} | |
public function set_unit($unit) { | |
$this->unit = $unit; | |
} | |
public function set_mode($mode) { | |
$this->mode = $mode; | |
} | |
public function set_language($language) { | |
$this->language = $language; | |
} | |
public function add_origin($origin) { | |
$this->origins[] = $origin; | |
} | |
public function add_destination($destination) { | |
$this->destinations[] = $destination; | |
} | |
public function get_api_api_key() { | |
return $this->api_key; | |
} | |
public function get_unit() { | |
return $this->unit; | |
} | |
public function get_mode() { | |
return $this->mode; | |
} | |
public function get_language() { | |
return $this->language; | |
} | |
public function get_distance() { | |
return $this->make_request(); | |
} | |
protected function make_request() { | |
$origins = implode('|', $this->origins); | |
$destinations = implode('|', $this->destinations); | |
$query_string = '?'; | |
$query_string .= 'origins=' . $origins; | |
$query_string .= '&destinations=' . $destinations; | |
$query_string .= '&key=' . $this->api_key; | |
$query_string .= '&mode=' . $this->mode; | |
$query_string .= '&unit=' . $this->unit; | |
$query_string .= '&language=' . $this->language; | |
$query_string = str_replace(' ', '+', $query_string); | |
$url = $this->endpoint . $query_string; | |
dsm($url); | |
try { | |
$ch = curl_init($url); | |
$response = curl_exec($ch); | |
curl_close($ch); | |
return $response; | |
} | |
catch (Exception $e) { | |
drupal_set_message($e->getMessage(), 'error'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment