我想在php中编写一个小类,它可以从不同的GEO-API(如Google Maps或osm nominatim)获取经度和纬度值。两个提供程序返回与json类似但具有不同键的结果。
在getCordinates()中,您会看到解析Google的api。是否有一个很好的设计模式,我没有必要使用几个if语句来破坏每个新地理提供程序的方法并炸毁方法但保持分离?
public $googleEndPoint = "http://maps.google.com/maps/api/geocode/json?address=";
public $OSMendPoint = "http://nominatim.openstreetmap.org/search?format=json&q=";
public $endpoint;
public $address;
function __construct($endpoint = 'google'){
switch ($endpoint){
case 'OSM':
$this->endpoint = $this->OSMendPoint;
break;
default:
$this->endpoint = $this->googleEndPoint;
break;
}
}
function request(){
$address = urlencode($this->address);
$result = file_get_contents($this->endpoint.$address);
$response = json_decode($result, true);
return $response;
}
function getCoordinates($address) {
$this->address = $address;
$response = $this->request();
// this is google specific and does not fit for other provider
if( $response['status']=='OK' ){
$data_arr['lat'] = $response['results'][0]['geometry']['location']['lat'];
$data_arr['lon'] = $response['results'][0]['geometry']['location']['lng'];
$data_arr['formatted_address'] = $response['results'][0]['formatted_address'];
return $data_arr;
} else {
return false;
}
}