A Simple Example

Welcome to our free jQuery Mobile tutorial. This tutorial is based on Webucator's jQuery Mobile course.

Contact Us or call 1-877-932-8228
A Simple Example

A Simple Example

Let's look at a simple page (IntegrationPhone/Demos/mapping.html) that pops up a JavaScript message with the user's latitude and longitude location. Users who visit our page will be prompted to explicitly allow our page to use their current location; see the left screenshot below. If they accept, our page will respond with their latitude and longitude, as on the right.

two iphone screenshots - geolocation example

Code Sample:


Code Explanation:

We test, with an if statement, for the presence of the navigator.geolocation object; if so, we call the getCurrentPosition function. We write two functions, locateSuccess and locateFail, to handle the success and failure cases, respectively.

On successful finding of the user's location, function locateSuccess is invoked. Note that, as discussed above, we can name this function anything we like (though, of course, a meaningful name containing "success" makes sense here), as long as the name of the function is the same name we use for the first parameter of the getCurrentPosition function. The loc parameter exposes a variety of information about the user's location; we assign loc.coords.latitude and loc.coords.longitude to two local variables, and show those values to the user in a JavaScript alert (popup) window.

If the user's location is not found, function locateFail is invoked. We use a JavaScript switch statement to evaluate parameter geoPositionError's code property: if 0, something unknown happened; if 1, the user denied permission; etc.

Of course, we could extend this application extensively: we might use Google's Places library to allow the user to perform a search for "bookstores" and to return human-friendly addresses (hopefully Nan & Bob's!), rather than latitude and longitude. Check out the Google Maps Demo Gallery for some inspiration and code samples.

The parameter passed to the success function, which we named loc in our example above, exposes a useful set of properties:

Position Properties
Property Units
coords.latitude degrees
coords.longitude degrees
coords.altitude meters (may be null)
coords.accuracy meters
coords.altitudeAccuracy meters (may be null)
coords.heading degrees clockwise (may be null)
coords.speed meters/second (may be null)
timestamp a date and time

This tutorial is based on Webucator's jQuery Mobile Course. We also offer many other Mobile Web Training courses. Sign up today to get help from a live instructor.