Using GeoLocation in a Web Browser

Posted by Mark Drew on code on April 17, 2011

Tagged under mobile

Having had an awesome time at WebDU, a couple of sessions had information about PhoneGap, JQuery Mobile and more importantly geolocation available in HTML 5 applications.

Some of the confusion arose from what the difference is between PhoneGap and JQuery Mobile provide.
Essentially, PhoneGap provides a common interface into the various API's provided on different movile devices. API's such as the Accelerometer, Camera, Compass, Geolocation, Contacts, Media and Notificaiton.
JQuery Mobile provides an API to develop a common UI that works across different devices as well as common ways for re-skinning and handling events within that UI.

A question come up about how to do GeoLocation within these devices and I pointed out that you can indeed do geolocation, and not only within a mobile device, but you can also do it using the HTML5 API's on desktop browsers.
This is actually really easy with the navigator.geolocation object in JavaScript.
To check whether you can actually use it all you have to do is check if this object exists in the DOM, with code like:

if (navigator.geolocation) \{ navigator.geolocation.getCurrentPosition(success, error); }

Now, if you run this code from some function, you will need to pass in two functions that will recieve the current position, or throw an error if there has been some problem getting the current location. The expanded code is shown below:

function getLocation()\{ if (navigator.geolocation) \{ navigator.geolocation.getCurrentPosition(success, error); } else \{ document.getElementById("output").innerHTML = "Your browser doesn't handle the GeoLocation API. Use Safari, Firefox 4 or Chrome"; } } function success(loc)\{ strout = ""; for(l in loc.coords)\{ strout += l +" = " +loc.coords[l] + "
"; } strout += ''; document.getElementById("output").innerHTML = strout; } function error(err)\{ document.getElementById("output").innerHTML = err.message; }

And that is it. No external libraries or PhoneGap API's. Just a standard browser call.
The navigator.geolocation.getCurrentPosotion() function will call the success(loc) function passing in a GeoPosition object that you can get the coordinates from. It also includes a few other handy properties such as longitude, lattitude, accuracy and heading if you are moving.
Check out a demo of the above code. There are no other libraries or includes so you can just view the source to see how it works.




comments powered by Disqus