Using Google Latitude to print current location

August 1, 2011

Updated version


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# latitude.py
#
# Copyright (c) 2011 Ruslan Valiyev
# ruslan@valiyev.com
#
import time
import urllib2
import simplejson as json
from geopy import geocoders

#
# Get your own keys at:
# http://code.google.com/apis/latitude/v1/getting_started.html#prereqs-getkey
# http://code.google.com/apis/maps/signup.html
#
GOOGLE_LATITUDE_KEY = 'your_key_goes_here'
GOOGLE_API_KEY = 'your_key_goes_here'
GOOGLE_URL = 'http://www.google.com/latitude/apps/badge/api?user=%s&type=json'

#
# Getting data in JSON
#
class GLatitude:
  def __init__(self,uid):
    self.uid=uid
  def getLocationData(self):
    return json.load(urllib2.urlopen(GOOGLE_URL % self.uid))
  def getCoords(self):
    return self.getLocationData()['features'][0]['geometry']['coordinates']
  def getTime(self):
    return self.getLocationData()['features'][0]['properties']['timeStamp']

#
# Convert epoch to human time
#
def TimeConvert(epoch):
  return time.strftime('%d %b %Y %H:%M', time.localtime(epoch))


def main():
  g = geocoders.Google(GOOGLE_API_KEY)
  gl = GLatitude(GOOGLE_LATITUDE_KEY)

  myLocation = gl.getCoords()
  myLocation.reverse()

  return TimeConvert(gl.getTime()), g.reverse(myLocation)

if __name__ == '__main__':
    print main()
Sample output:

>>> import latitude
>>> latitude.main()
('04 Aug 2011 08:42', (u'A1 motorway, 1218 Grand-Saconnex, Switzerland',
(46.239181299999998, 6.1208168000000001)))
PS. Don't forget to grab the latest version of geopy.