Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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.
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 microsoft.com. 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.
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.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 98529 Viewers
61 Video lessons · 85819 Viewers
71 Video lessons · 69720 Viewers
56 Video lessons · 102030 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
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.
Your file was successfully uploaded.