Yahoo GeoLocation API
July 13th, 2007The Yahoo Maps API is the best API I’ve found for using on in internal site. Google won’t let me access theirs from a non-public site.
I messed around with their code to to Latitude/Longitude lookups on UK postcodes.
Include the API JS.
<script type="text/javascript" src="http://api.maps.yahoo.com/v2.0/fl/javascript/apiloader.js"></script>
Heres the two PHP functions that do the hard work.
Make sure your /tmp is writable.
function request_cache($url, $dest_file, $timeout=43200) {
if(!file_exists($dest_file) || filemtime($dest_file) < (time()-$timeout)) {
$stream = fopen($url,'r');
$tmpf = tempnam('/tmp','YWS');
file_put_contents($tmpf, $stream);
fclose($stream);
rename($tmpf, $dest_file);
}
}
function yahoo_geo($location) {
$q = 'http://api.local.yahoo.com/MapsService/V1/geocode';
$q .= '?appid=rlerdorf&location='.rawurlencode($location);
$tmp = '/tmp/yws_geo2_'.md5($q);
request_cache($q, $tmp, 43200);
libxml_use_internal_errors(true);
$xml = simplexml_load_file($tmp);
if ($xml) {
$ret['precision'] = (string)$xml->Result['precision'];
foreach($xml->Result->children() as $key=>$val) {
if(strlen($val)) $ret[(string)$key] = (string)$val;
}
return $ret;
}
}
Here’s some code that loops over a database and looks up the latitude & longitude from a UK postcode.
Obviously change to suit your requirements.
$rs = $conn->execute('SELECT postcode FROM table');
echo '<pre>';
foreach($rs as $foo){
$latlon = yahoo_geo($foo['postcode']);
print_r($latlon);
}
echo '</pre>';
| Bookmark it del.icio.us | Reddit | Slashdot | Digg | Facebook | Technorati | Google | StumbleUpon | Window Live | Tailrank | Furl | Propeller | Yahoo |
Was this post useful to you? Let me know, buy me a beer!
Alternatively, if you're feeling impecunious, you may like to subscribe to my RSS feed, or see other articles in the PHP category.