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.

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.

Determining position with geolocation

One of the more exciting features available to web developers working on mobileweb applications is the ability to determine location of the user's device usingthe Geolocation API.The Geolocation API lets you figure out where a device's physical position ison 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, Icould 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 theuniversal 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 ofdisplaying this data, you would need to use a third-party API, like the Bing MapsAPI or Google Maps API.

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

Or alternatively, like we talked about earlier, I can use Modernizr and I canask Modernizr if geolocation is supported.And if it is, it's safe to go ahead and use the Geolocation API; otherwise, Iwould 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 yourcurrent position?" and it tells you. Or there's the continuous method in whichcase your code can set up a position-watcher,and every time the device moves more than a certain threshold amount, theCallback 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 usethe APIs successfully.First, you'll notice that the getCurrentPosition and watchPosition functionsboth take a successCallback, an errorCallback, and an options parameter.Now the successCallback is called whenever the API is able to successfullylocate the device; the errorCallback is called when location was unable to beobtained; and the options parameter provides some various options forobtaining location.

In the case of the watchPosition function, it returns a watchID, and this isvery similar to using a JavaScript function like setInterval or setTimeoutwhere 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, whichcontains 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 conditionor 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 thebest 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 resultin a longer response time, or it might fire up a GPS device that increases powerconsumption, 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 celltower locations or Wi-Fi locations, that kind of stuff.There's also the timeout parameter, which is how long the application is willingto wait for results in milliseconds.So if you are willing to wait for 10 seconds, you would pass a value of10,000 for timeout.The maximumAge specifies that the application will accept cached locationinformation that's no older than the specified value.

And if the current application has a value that's older than that, this willcause 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 canpass in some parameters.So for example, I would say enableHighAccuracy and set it to true if I wantedto. 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 highaccuracy, and give me results that are up to two minutes old."To handle error conditions, the error object that gets called back willcontain two things.

First is the code, and the code is an integer number that indicates whysomething 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 outwhere it was, and then there's TIMEOUT in which case the device just took toolong 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 wouldlook at the code to see what happens and then perhaps display results to theuser 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 containsfurther 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 bythe 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 thelocation is within meters.

If the device supports things like altitude and altitudeAccuracy, those arereported 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 afallback if it doesn't.For example, you might let the user manually enter a location or a ZIP code orsomething like that.Remember that the user might deny the disclosure of their location becauseaccording to the W3C, devices have to ask the user if it's okay if theirlocation gets disclosed.

And if they say okay, they have the option of adding your site to awhitelist 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 unlessyou really need it because this may cause increased power consumption or longer response times.Usually, the location information that comes back from whatever method thedevice 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 thatyou can look at for further reading to see how to use longitude and latitude toobtain 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 hereoff of microsoft.com.This is your starting point if you want to build a web application for mobilethat 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 differentforms 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 youwant 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 goingto go to my snippets file here, and you can see that I'm here in theGeoLocation 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 informationfor the device, for longitude, latitude, accuracy, and whatever else thedevice might provide.So let's go back to the code.I need to fill out this getLocation function, and when the window loads, it'sgoing to call the getLocation function.And if getLocation is successful, it's going to fill out the spans you see herewith 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'mincluding 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 callthe 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 settingthe content of those spans to the value of the coords object that comes backfrom 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 todisclose 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 itremember that I either said yes or no, so I'm just going to turn that off andsay 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 theAltitude Accuracy is 5.So apparently, what's happening is the device is saying, "I can't get yourAltitude, 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 somekind of altitude-reading device, whatever it is, and it's able to providethat 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 serviceslike address finding or mapping.

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

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.

Already a member ?

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

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com 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.

Thanks for signing up.

We’ll send you a confirmation email shortly.

Sign up and receive emails about lynda.com and our online training library:

new course releases

newsletter

general communications

special notices

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 lynda.com.

Sign up and receive emails about lynda.com and our online training library:

new course releases

newsletter

general communications

special notices

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