Techblog Careesma Just another Network site

5May/10Off

Geolocateme with javascript!

New mobile phones (like iphone or android ones) have come out with some wonderful GPS features! And thanks to the W3C guys and their Geolocation API Specification, we can find the location of our web users (always to give them new features and services of course).

Mobile browsers offer us some DOM objects to control and find the user's location. As you know, I don't wanna fill this blog with empty words so let's see an example of that. I think it's the best way to learn!

function worksfine(position) {
	/* Geolocalisation works fine.
            position object:
                 position.coords.latitude -> Latitude
                 position.coords.longitude -> Longitude
                 position.coords.accuracy -> Accuracy
                 position.coords.altitude -> Altitude (not always available)
                 position.coords.altitudeAccuracy -> Altitude Accuracy (not always available)
                 position.coords.speed -> Speed (not always available)
                 position.coords.heading -> Heading (not always available)
        */
        alert('Your position is '+position.coords.latitude+' (lat) x '+position.coords.longitude+' (lon)');
}

function thereserror(error) {
        alert('There is an error '+error.code+' : '+error.message);
}

if (navigator.geolocation) {
	/* Code if geolocation is available. */
        /* worksfine and thereserror are callback functions that are called when geolocation is finished depending on the results */
        /* maximumAge:600000 = 10 minutes (600000 milliseconds) */
        navigator.geolocation.getCurrentPosition(worksfine, thereserror, {enableHighAccuracy:true,maximumAge:600000});
} else {
	/* Code if geolocation is not available */
}

As you can see by that piece of code, geolocation is not a synchronous operation; that's the reason for the callback functions.

On the other hand, the phone with GPS features always asks permission to calculate that information (for obvious security reasons).

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

About Albert Horta

No description. Please complete your profile.
Comments (0) Trackbacks (2)

Leave a comment