Skip to content

Instantly share code, notes, and snippets.

@MauMaGau
Created April 4, 2012 13:46
Show Gist options
  • Save MauMaGau/2301153 to your computer and use it in GitHub Desktop.
Save MauMaGau/2301153 to your computer and use it in GitHub Desktop.
PHP: GeoNames class
<?php
/* GeoCode class */
// Usage
$Geonames = new Geonames();
print_r( $Geonames->geocode_postcode('SW1A 0AA','username') );
if( ! empty($Geonames->message) ){
echo $Geonames->message;
}
class Geonames{
public $message = '';
public function geocode_postcode($postcode, $username) { // Sign up for a free username at http://www.geonames.org/
if( ! $this->valid_postcode($postcode)){
$this->message = 'Please enter a valid postcode';
return FALSE;
}
$postcode = str_replace(' ','',$postcode);
if(strlen($postcode)>4){ // ensure the postcode has the appropriate space
$postcode = wordwrap($postcode, strlen($postcode)-3,'%20', true);
}
$url = "http://api.geonames.org/postalCodeSearchJSON?formatted=true&postalcode=$postcode&country=UK&username=$username&maxRows=1&style=short";
//echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
// $data should be: stdClass Object ( [postalCodes] => Array ( [0] => stdClass Object ( [postalCode] => *the postcode* [countryCode] => UK [lng] => -dd.dddddd [placeName] => *nearest town* [lat] => nn.nnnnnn ) ) )
//print_r($data);
if(isset($data->postalCodes) && !empty($data->postalCodes)){
$return['lat'] = $data->postalCodes[0]->lat;
$return['lng'] = $data->postalCodes[0]->lng;
$return['town'] = $data->postalCodes[0]->placeName;
return $return;
}
if(empty($this->message)){
$this->message = 'An error occured whilst fetching geo data';
}
return FALSE;
}
private function valid_postcode($postcode) {
// Regex to validate a full UK postcode (eg SW1A 0AA)
$regex = '!^([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw])\ {0,1}[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}|([Gg][Ii][Rr]\ 0[Aa][Aa])|([Ss][Aa][Nn]\ {0,1}[Tt][Aa]1)|([Bb][Ff][Pp][Oo]\ {0,1}([Cc]\/[Oo]\ )?[0-9]{1,4})|(([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[BFSbfs][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]|[Tt][Kk][Cc][Aa])\ {0,1}1[Zz][Zz]))$!';
$result = preg_match($regex, $postcode);
if($result > 0) {
return TRUE;
} elseif(strlen($postcode) < 5 ) {
// Regex to validate a half UK postcode (eg SW1A)
$regex = '([A-PR-UWYZa-pr-uwyz]([0-9]{1,2}|([A-HK-Ya-hk-y][0-9]|[A-HK-Ya-hk-y][0-9]([0-9]|[ABEHMNPRV-Yabehmnprv-y]))|[0-9][A-HJKS-UWa-hjks-uw]))';
$result = preg_match($regex, $postcode);
if($result > 0){
return TRUE;
}
}
return FALSE;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment