The current issue of the German c’t magazine was in my post box this afternoon, and I went to get it when Joerg Wende pointed out that it carries an article which explains how to use the Android Tasker app to periodically publish a device’s location to a Web page in a way similar to how Google Latitude used to operate. Does that sound familiar to you? :-)

Apart from Tasker costing a few Euros, and aside from the fact that it’s Android only, there are plenty of issues with that article, but instead of complaining, I’ll show you how you can use OwnTracks to do similarly, albeit with a number of benefits including immediate reporting of location change. If you’re new to MQTT, I’d like to suggest you start reading here for a bit of an introduction.

architecture

OwnTracks runs on your smartphone and publishes a JSON payload to your MQTT broker when it detects significant movement. That payload looks like this:

{
  "_type": "location", 
  "acc": "165", 
  "batt": "65", 
  "lat": "47.056987", 
  "lon": "10.623918", 
  "tst": "1389104761"
}

We’re going to create a small program which subscribes to the broker and writes the last obtained location into a file.

#!/usr/bin/env python

import mosquitto
import json

URLFMT = "https://maps.google.com/?q=%s,%s\n"

def on_message(mosq, userdata, msg):
    try:
        data = json.loads(str(msg.payload))
    except:
        print "Can't decode payload"
    try:
        f = open('location.current', 'w')
        f.write(URLFMT % (data['lat'], data['lon']))
        f.close()
    except Exception, e:
        print "Can't write file: %s" % str(e)

mqttc = mosquitto.Mosquitto()
mqttc.on_message = on_message

mqttc.connect("localhost", 1883, 60)
mqttc.subscribe("owntracks/jpm/nex4", 0)

mqttc.loop_forever()

Our little program decodes the JSON payload it receives and uses the lat and lon values therein to write the URL to the map into a file. The resulting file contains something like this:

https://maps.google.com/?q=47.056987,10.623918

Our Web page will, when loaded, use that file to load Google map into an iFrame, though we won’t write the code for the latter (it’s in the magazine Update: example here).

Also, note that there are far neater solutions, such as using Websockets to get instant notification on the map directly from the MQTT broker: see a version for OSM and one for Google maps.

If you take into account that OwnTracks is free of charge, and that it reports a device’ (Android and iPhone) location when movement is detected, I believe we have the better solution. We’re also able to detect geo fences (leaving or entering an area of arbitrary radius around a point), and you can set your broker to allow friends and family to see eachother’s location

Interested? Read about OwnTracks, get the apps, and off you go! Enjoy.

GPS, MQTT, and OwnTracks :: 11 Jan 2014 :: e-mail