Last active
September 27, 2019 08:38
-
-
Save mortensassi/085fce87dfbffd0a3e8164784122bb8f to your computer and use it in GitHub Desktop.
PHP Class for reverse querying the openstreetmaps api
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 | |
use GuzzleHttp\Client; | |
class esdeGeo { | |
/** | |
* Constructor with all needed parameters | |
* | |
* @param [type] $lat | |
* @param [type] $lon | |
* @param string $lang | |
* @param integer $zoom | |
* @param string $format | |
*/ | |
function __construct($lat = null, $lon = null, $lang = 'en', $zoom = 16, $format = 'json') { | |
$this->api = 'https://nominatim.openstreetmap.org/reverse?namedetails=1&'; | |
$this->lang = $lang; | |
$this->format = $format; | |
$this->zoom = $zoom; | |
$this->lat = $lat; | |
$this->lon = $lon; | |
$this->response = null; | |
} | |
/** | |
* Build the query | |
* | |
* @return void | |
*/ | |
private function buildQuery() { | |
$url = $this->api . 'format=' . $this->format . '&zoom=' . $this->zoom . '&lat=' . $this->lat . '&lon=' . $this->lon . '&accept-language=' . $this->lang; | |
return $url; | |
} | |
/** | |
* Set Response of API Call | |
* | |
* @return void | |
*/ | |
private function setResponse() { | |
$url = $this->buildQuery(); | |
$client = new GuzzleHttp\Client; | |
$response = $client->get($url); | |
if ($response->getStatusCode() == 200) { | |
$body = $response->getBody(); | |
$body = (string)$body; | |
$body = json_decode($body); | |
$this->response = $body; | |
} else { | |
return false; | |
} | |
return true; | |
} | |
/** | |
* getCountryname | |
* | |
* @return void | |
*/ | |
public function getCountry() { | |
if (empty($this->response)) { | |
$this->setResponse(); | |
} | |
$country = $this->response->address->country; | |
if ($country == 'PRC' && $this->lang == 'en') { | |
$country = 'China'; | |
} elseif($this->response->address->country_code == 'es') { | |
$re = '/ \(([^)]+)\)/m'; | |
preg_match_all($re, $country, $matches, PREG_SET_ORDER, 0); | |
if (isset($matches[0]) && isset($matches[0][0])) { | |
$country = str_replace($matches[0][0], '', $country); | |
} | |
} | |
return $country; | |
} | |
/** | |
* Get the Country code | |
* | |
* @return void | |
*/ | |
public function getCountryCode() { | |
if (empty($this->response)) { | |
$this->setResponse(); | |
} | |
$country_code = $this->response->address->country_code; | |
return $country_code; | |
} | |
/** | |
* Get the Data and set the response | |
* | |
* @return void | |
*/ | |
public function getData() { | |
if (empty($this->response)) { | |
$this->setResponse(); | |
} | |
return $this->response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment