Start your free trial now, and begin learning software, business and creative skills—anytime, anywhere—with video instruction from recognized industry experts.

Start Your Free Trial Now

Determining position with geolocation


Mobile Web Design & Development Fundamentals

with Joe Marini

Video: Determining position with geolocation

One of the more exciting features available to web developers working on mobile web applications is the ability to determine location of the user's device using the Geolocation API. The Geolocation API lets you figure out where a device's physical position is on the planet, and the way you do that is by asking the device where it is. So let's suppose I have my world here and I was in some city, say Seattle, I could ask the device, "Hey, where are you?" And the advice can respond back and say, "Here I am.
Expand all | Collapse all
  1. 2m 48s
    1. Welcome
      1m 2s
    2. Using the exercise files
      1m 46s
  2. 29m 25s
    1. Understanding the mobile context
      8m 5s
    2. A survey of mobile sites
      11m 44s
    3. Targeting mobile browsers
      4m 31s
    4. Previewing a complete mobile site
      5m 5s
  3. 27m 20s
    1. Designing for one web
      3m 43s
    2. Using well-defined web standards
      3m 45s
    3. Designing mobile-friendly pages
      3m 40s
    4. Being crisp, clean, and succinct
      5m 45s
    5. Minimizing input where possible
      6m 47s
    6. Focusing on the core scenarios
      3m 40s
  4. 1h 13m
    1. Installing the tools
      3m 52s
    2. Setting up a local web server
      9m 13s
    3. Installing device emulators
      17m 5s
    4. Using device emulators
      13m 9s
    5. Downloading Modernizr and Mobile Boilerplate
      6m 22s
    6. Building a first mobile web page
      5m 43s
    7. Developing mobile pages with desktop browsers
      8m 6s
    8. Exploring useful mobile web development resources
      10m 23s
  5. 53m 26s
    1. Reviewing mobile markup languages
      5m 10s
    2. Understanding content adaptation approaches
      10m 32s
    3. Controlling the viewport layout
      12m 50s
    4. Designing forms
      13m 30s
    5. Using CSS media queries
      11m 24s
  6. 1h 11m
    1. Detecting client capabilities with script
      10m 8s
    2. Caching information with local storage
      9m 16s
    3. Determining position with geolocation
      12m 52s
    4. Minimizing HTTP requests with data URLs
      7m 39s
    5. Understanding user agent detection
      9m 8s
    6. Using server-side detection with PHP
      6m 52s
    7. Using server-side detection with ASP.NET
      4m 54s
    8. Using HTML5 Boilerplate for mobile
      11m 6s
  7. 39m 22s
    1. Measuring performance
      7m 41s
    2. Creating full-screen web apps
      6m 30s
    3. Customizing the user interface
      5m 14s
    4. Detecting orientation changes
      3m 58s
    5. Detecting device movement
      5m 21s
    6. Using touch events
      10m 38s
  8. 47m 14s
    1. Taking a look at the finished site
      7m 40s
    2. Examining the header and background image style on the Home page
      10m 10s
    3. Examining the hover effect and layout styles on the Tours page
      6m 42s
    4. Examining mobile forms on the Contact page
      9m 45s
    5. Viewing and testing the mobile site on emulators
      8m 11s
    6. Viewing the site on devices
      4m 46s
  9. 2m 34s
    1. Goodbye
      2m 34s

please wait ...
Watch the Online Video Course Mobile Web Design & Development Fundamentals
5h 47m Beginner Jul 20, 2011

Viewers: in countries Watching now:

This course surveys the core principles and techniques essential to building web sites for mobile devices. Author Joe Marini introduces the mobile context, sheds light on its unique coding requirements, and discusses interface design techniques that enhance existing sites for mobile viewing. The course shows how to approach designing for mobile form factors such as smaller screens and finger-based interaction, along with how to incorporate CSS3 and HTML5 capabilities, such as geolocation, local storage, and media queries.

Topics include:
  • Implementing well-defined web standards
  • Working with Modernizr and Mobile Boilerplate
  • Building a first mobile web page
  • Understanding content adaptation strategies
  • Designing forms for mobile
  • Detecting client capabilities with script
  • Using server-side detection with PHP and ASP.NET
  • Working with mobile browser capabilities
  • Viewing and testing the mobile site on device emulators
Developer Web
Joe Marini

Determining position with geolocation

One of the more exciting features available to web developers working on mobile web applications is the ability to determine location of the user's device using the Geolocation API. The Geolocation API lets you figure out where a device's physical position is on the planet, and the way you do that is by asking the device where it is. So let's suppose I have my world here and I was in some city, say Seattle, I could ask the device, "Hey, where are you?" And the advice can respond back and say, "Here I am.

I am at -122.34 degrees longitude and 47.61 degrees latitude." And that information tells me where I am in longitude and latitude, which is the universal way of providing location on the globe. Location is always given in longitude and latitude. In order to convert this to a real address, or a map, or some other method of displaying this data, you would need to use a third-party API, like the Bing Maps API or Google Maps API.

And when we get finished with this example, I'm going to point you some resources you can use to do that, because it's a little bit beyond the scope of this example to show you all the ins and outs of various third-party mapping applications. So let's get started. The geolocation features are accessed from the geolocation object, which itself is located from the navigator object. And you can see here I'm using a little bit of script code to see if the geolocation feature is present in the browser by testing to see if navigator.geolocation is not null.

Or alternatively, like we talked about earlier, I can use Modernizr and I can ask Modernizr if geolocation is supported. And if it is, it's safe to go ahead and use the Geolocation API; otherwise, I would have to do some fallback method or just not provide the feature. There are two ways to get location information. There's the one-shot method where you just ask the device, "Hey, what's what your current position?" and it tells you. Or there's the continuous method in which case your code can set up a position-watcher, and every time the device moves more than a certain threshold amount, the Callback function will be called and you will be told that the device moved to a new location.

In either case, there are some common things you have to do in order to use the APIs successfully. First, you'll notice that the getCurrentPosition and watchPosition functions both take a successCallback, an errorCallback, and an options parameter. Now the successCallback is called whenever the API is able to successfully locate the device; the errorCallback is called when location was unable to be obtained; and the options parameter provides some various options for obtaining location.

In the case of the watchPosition function, it returns a watchID, and this is very similar to using a JavaScript function like setInterval or setTimeout where you get a timerID, and then if you want to stop the watcher later, you simply call clearWatch with the watchID. The successCallback and errorCallback functions take arguments as well. In the case of the successful callback, it takes a positionInfo object, which contains information about the position of the device. In the case of the errorCallback, it takes an object called positionErrorInfo, and you can use that data to see what went wrong and report the error condition or take some other action.

For the options parameter, you pass a JavaScript object that specifies a couple of things. First, whether or not you want to enable high accuracy, and that parameter, which is either true or false, indicates that the web page would like to get the best possible location results as long as the device is able to provide them. The reason why you might want to set this to false is because this could result in a longer response time, or it might fire up a GPS device that increases power consumption, and it defaults to be in false.

So you can specify true if you want the device to provide highly accurate data. If it can't use GPS, it will usually try to use some other information like cell tower locations or Wi-Fi locations, that kind of stuff. There's also the timeout parameter, which is how long the application is willing to wait for results in milliseconds. So if you are willing to wait for 10 seconds, you would pass a value of 10,000 for timeout. The maximumAge specifies that the application will accept cached location information that's no older than the specified value.

And if the current application has a value that's older than that, this will cause a refresh of the location data. So essentially, you would call it like this. You would call navigator.geolocation with getCurrentPosition. You give it the names of the success and error functions, and then you can pass in some parameters. So for example, I would say enableHighAccuracy and set it to true if I wanted to. The timeout would be 10 seconds, and the maximumAge would be 120 seconds, or two minutes. So this call says, "I'm willing to wait 10 seconds for the results I want high accuracy, and give me results that are up to two minutes old." To handle error conditions, the error object that gets called back will contain two things.

First is the code, and the code is an integer number that indicates why something went wrong. It can either be PERMISSION_DENIED, in which case the user said, "No, you can't have my position." There's POSITION_UNAVAILABLE which means that the device couldn't figure out where it was, and then there's TIMEOUT in which case the device just took too long to get the location and your error function was called. The message parameter contains any associated error message from the device. This is not intended to be shown to the user. It's primarily just for your debugging information.

You might write an error handler function that looks something like this. You have function error, then we take an errorInfo object, and then you would look at the code to see what happens and then perhaps display results to the user in the form of 'permission was denied' or 'something went wrong' or 'timed out' or something like that. Handling success conditions is pretty similar. When the success function gets called, it would pass an object that contains two properties. The first one is called coords, and that is a coordinates object that contains further information about the location.

And a timestamp, and that's the time in milliseconds that the location was last obtained. The coords object looks like this. It has longitude, latitude, and accuracy. These first three properties--longitude, latitude, and accuracy--are required by the W3C to be supported. The other four, altitude, altitudeAccuracy, heading, and speed are not required, but some implementations provide them. The longitude and latitude are pretty self-explanatory. They tell you where the device is, and the accuracy tells you how accurate the location is within meters.

If the device supports things like altitude and altitudeAccuracy, those are reported in meters as well. And heading is reported in degrees. Speed is reported in meters per second. There are some things to remember about using geolocation. First, always check to see if the device supports location and provide a fallback if it doesn't. For example, you might let the user manually enter a location or a ZIP code or something like that. Remember that the user might deny the disclosure of their location because according to the W3C, devices have to ask the user if it's okay if their location gets disclosed.

And if they say okay, they have the option of adding your site to a whitelist that's always allowed to have your location, or they can do on a one-by-one basis. But remember, the user might say no. Don't ask for high accuracy data unless you really need it because this may cause increased power consumption or longer response times. Usually, the location information that comes back from whatever method the device is using is usually accurate enough. The location is always returned as a longitude and a latitude. To do anything further with the data requires using an additional library.

And before we actually go look at the code, let me show you some web sites that you can look at for further reading to see how to use longitude and latitude to obtain position on a map. I've got three web sites here. The first one is the Bing Maps API and you can see the URL I provided up here off of This is your starting point if you want to build a web application for mobile that uses location information. The SDK is fully documented. You basically just get a developer key and you're off and running. Same thing goes for Google.

Google also has a Maps API. Same idea, you register as a developer, you get a key, and then there's various different forms of the Maps API that you can use. There's one for JavaScript. There's one for Flash. There's one for Static Maps. There's a whole bunch of different ways to get maps. MapQuest also provides developer services. You register as a developer and get a key. It's a pretty common pattern. And then you use their Geocoding services or what other mapping services you want to use to either retrieve addresses or maps or whatever else. Let's take a look at the code. So here I'm in my code, and this is the geolocation_start file. And I'm going to go to my snippets file here, and you can see that I'm here in the GeoLocation section.

So what we're going to do, let me show you this in Design mode, so we are going to use the geolocation object to retrieve the information for the device, for longitude, latitude, accuracy, and whatever else the device might provide. So let's go back to the code. I need to fill out this getLocation function, and when the window loads, it's going to call the getLocation function. And if getLocation is successful, it's going to fill out the spans you see here with the location information that comes back.

So let's go get that. First, I'm going to copy the code that detects to see if location is supported, and that goes right there. So we're asking Modernizr if geolocation is present, and you can see I'm including the Modernizr script right here. And I'm going to copy the Success and Error functions, and I'm going to paste those in. Okay. So what's going to happen is if geolocation is supported, we're going to call the getCurrentPosition function and we're going to pass in the Success and Error callbacks.

And in the Success function, you can see that what's happening is we're setting the content of those spans to the value of the coords object that comes back from the positionInfo object. And if there's an error, then we'll report error codes as they happen. So let's go ahead and save. All right! Let's go ahead and copy geolocation_start into our folder, and let's try this out.

Let's try it out in Opera first. And you can see that when I bring up the page in the browser, I'm being asked to disclose my location, so I can either agree or disagree, so I'm going to agree. And then it says, "The device wants to know your location." And I can have it remember that I either said yes or no, so I'm just going to turn that off and say go ahead and share my location. And you can see that it went out and got my location, so here I am at longitude -119 and latitude of 34.27, and I'm accurate to within a very large distance, so that's 22,000 meters.

So this is using the Wi-Fi of the emulator to get the location. And that's probably where Ventura, California is what's where I'm recording it. Let's do the same thing over in Windows Phone. Now I believe Windows Phone uses an emulation layer to provide geolocation data, so I will say localhost. And then once again I'm being asked to share my location, and I will say yes, and you can see once again location data is being provided.

Now in this case, you can see that there is no altitude, altitude accuracy, heading, or speed provided in this implementation. Over here we've got some interesting results. I've got, first of all, different values for my location. This is probably cached data for Seattle. And in Altitude I have null, but the Altitude Accuracy is 5. So apparently, what's happening is the device is saying, "I can't get your Altitude, but if I was able to get it, this is how accurate I would be." So the emulator is emulating some kind of barometric pressure reader or some kind of altitude-reading device, whatever it is, and it's able to provide that information for me.

So using the Geolocation API, you can figure out where a device is located on the planet. And by doing a little bit further extra work, you can provide advanced services like address finding or mapping.

There are currently no FAQs about Mobile Web Design & Development Fundamentals.

Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.

Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

* Estimated file size

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.

Mark all as unwatched Cancel


You have completed Mobile Web Design & Development Fundamentals.

Return to your organization's learning portal to continue training, or close this page.


Upgrade to View Courses Offline


With our new Desktop App, Annual Premium Members can download courses for Internet-free viewing.

Upgrade Now

After upgrading, download Desktop App Here.

Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Start your FREE 10-day trial

Begin learning software, business, and creative skills—anytime,
anywhere—with video instruction from recognized industry experts. provides
Unlimited access to over 4,000 courses—more than 100,000 video tutorials
Expert-led instruction
On-the-go learning. Watch from your computer, tablet, or mobile device. Switch back and forth as you choose.
Start Your FREE Trial Now

A trusted source for knowledge.


We provide training to more than 4 million people, and our members tell us that helps them stay ahead of software updates, pick up brand-new skills, switch careers, land promotions, and explore new hobbies. What can we help you do?

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from

Sign up and receive emails about and our online training library:

Here’s our privacy policy with more details about how we handle your information.

submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.