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. I don't really recommend it. But still. People asked.

<?

//v2.1: Properly decodes JSON using PHP's inbuilt functions
//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");

$latitude=json_decode($info,true);
$place=$latitude["features"]["0"]["properties"]["reverseGeocode"];
$timestamp=$latitude["features"]["0"]["properties"]["timeStamp"];

echo 
"I was last seen in: $place (".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