James Cridland

Google Latitude on your website

On my front page there's currently a piece of info letting you know where I am.

I get this from Google Latitude. Here's how to do it...

1. Turn on your blog badge. I've only turned-on my city-level location.
2. Scroll down the blog badge page again, and copy the user ID within the JSON feed that's suddenly appeared.
3. Use this code. Hey presto.

Incidentally, this code has no caching on it; nor any error-checking. It's a nasty way of parsing JSON. I don't really recommend it. But still. People asked.

<?

//v2: now returns time since I last checked in to Google Latitude.

$info file_get_contents("http://www.google.com/latitude/apps/badge/api?user=<yourID>&type=json");

$timestamp=substr($info,strpos($info,"timeStamp")+strlen("timestamp")+1);
$timestamp=substr($timestamp,strpos($timestamp," ")+1);
$timestamp=substr($timestamp,0,strpos($timestamp,","));

$info=substr($info,strpos($info,"reverseGeocode")+strlen("reverseGeocode")+1);
$info=substr($info,strpos($info,"\"")+1);
$info=substr($info,0,strpos($info,"\""));
echo 
"I was last seen in: $info (".getRelativeTime($timestamp).")";

function 
plural($num) {
    if (
$num != 1)
        return 
"s";
}

function 
getRelativeTime($date) {
    
$diff time() - $date;
    if (
$diff<60)
        return 
$diff " second" plural($diff) . " ago";
    
$diff round($diff/60);
    if (
$diff<60)
        return 
$diff " minute" plural($diff) . " ago";
    
$diff round($diff/60);
    if (
$diff<24)
        return 
$diff " hour" plural($diff) . " ago";
    
$diff round($diff/24);
    if (
$diff<7)
        return 
$diff " day" plural($diff) . " ago";
    
$diff round($diff/7);
    if (
$diff<4)
        return 
$diff " week" plural($diff) . " ago";
    return 
"on " date("F j, Y"strtotime($date));
}
?>

Download this code