Monday, December 24, 2012

Geolocation with Brython

Brython keywords

We used the doc keyword previously, in another article. How about using the win keyword this time? How about something for mobile apps?

Geolocation

To access geolocation services in your web browser, in Javascript you need to use the methods of window.navigator.geolocation. That means win.navigator.geolocation in Brython.

I'm lazy, so i'll assign it once:

geo = win.navigator.geolocation

Next I'll define a callback function for success and error:

def navi(pos):
    log('Position acquired')
    xyz = pos.coords
    display = "Your position: %f,%f" % (xyz.latitude, xyz.longitude)
    alert(display)
    log(pos.timestamp)
    log(xyz.latitude)
    log(xyz.longitude)
    log(xyz.accuracy)
    log(xyz.altitude)
    log(xyz.altitudeAccuracy)
    log(xyz.heading)
    log(xyz.speed)

def nonavi(error):
    log(error)

Alright, now we are ready to actually try to get a position:

if geo:
    geo.getCurrentPosition(navi, nonavi)
else:
    alert('geolocation not supported')

Full code

It is pretty straightforward:

<!DOCTYPE html>
<html>
    <head>
        <title>Brython test</title>
        <script src="brython.js"></script>
    </head>
    <body onLoad="brython()">
        <script type="text/python">
        geo = win.navigator.geolocation

        def navi(pos):
            log('Position acquired')
            xyz = pos.coords
            display = "Your position: %f,%f" % (xyz.latitude, xyz.longitude)
            alert(display)
            log(pos.timestamp)
            log(xyz.latitude)
            log(xyz.longitude)
            log(xyz.accuracy)
            log(xyz.altitude)
            log(xyz.altitudeAccuracy)
            log(xyz.heading)
            log(xyz.speed)

        def nonavi(error):
            log(error)

        if geo:
            geo.getCurrentPosition(navi, nonavi)
        else:
            alert('geolocation not supported')
        </script>
    </body>
</html>

No comments:

Post a Comment