HTML5, 20 Lessons to Successful Web Development (2015)
PART III Advanced HTML5
LESSON 15 Supporting Geolocation
To view the accompanying video for this lesson, please visit mhprofessional.com/nixonhtml5/.
With the incredible rise in popularity of smartphones, the ability to determine the location of a device has become almost essential, particularly for running interactive maps and navigation software, and even for finding local Wi-Fi hotspots, or services such as restaurants or cash dispensing machines, and so on.
Geolocation is also being used more and more to try to sell you services by offering promotions in stores that are near to you, and a little more benevolently in enabling you to know whether friends or acquaintances are within your near vicinity. Thankfully, you are in control of when you allow your location information to be revealed, so you can minimize any privacy or security risks the technology could create.
The geolocation Property
The first thing you must do when accessing geolocation is to determine whether or not it is available by testing the geolocation property, like this (preceding the property with the navigator object name):
If geolocation is supported, the part of code after the else statement is executed, and that’s where your code that uses the geolocation information goes, as follows.
The getCurrentPosition() Function
Once you know that a browser supports geolocation, you may ask it for its current position using the getCurrentPosition() function, like this:
This line of code calls the browser’s geolocation software, passing it the names of two new functions called granted() and denied(). Because the function names (and not the actual function contents) are being passed to the getCurrentPosition() function, no parentheses are placed after the names.
One or the other of these two functions will be called back by the browser according to whether the user grants or denies you the use of its location data. Therefore both of these routines must be written.
A granted() Function
Here’s what an example granted() function might look like:
In this instance I have opted to simply display the returned location information in an alert() message window. You will be more likely to display a map or perform other functions based on this information. As for the user’s location, this is returned in the following two properties:
The former property holds the latitude value and the latter the longitude.
A denied() Function
If the user has chosen not to allow the browser’s location data to be revealed to your code, then your denied() function will be called, and an error code will be given to state why.
Here’s an example denied() function:
This code is a little longer because it processes the value in error.code, which can be a number between 1 and 4, as follows:
1. Permission Denied
2. Position Unavailable
3. Operation Timed Out
4. Unknown Error
Again, I have chosen a simple alert() message to provide this information. In your code (if you choose to give a message at all), you may wish to display a simpler and more friendly phrase such as “Geolocation request denied.”
In the Real World
Here’s a complete document you can use to display a Google map of a user’s current location in a <div> element, based on the coordinates returned by the browser’s geolocation code. If permission is not given or the browser doesn’t support geolocation, then a message stating that is provided by writing directly into the contents of the <div> tag with the id of status using its innerHTML property.
When a web page containing this code is loaded into a browser, the first thing that happens is a request is made to the user. Depending on the browser and operating system in use, this may be presented in a variety of different ways. On Google Chrome, for example, it looks like Figure 15-1.
FIGURE 15-1 The geolocation request displayed by Google Chrome
If permission is not given, then only a short message will be displayed, but if it is given, then the result will be similar to Figure 15-2.
FIGURE 15-2 Permission has been granted and a map is displayed.
When using the Google Maps service, you can modify the arguments to the gopts object (highlighted in bold in the following code) to modify the type of map displayed:
The variables you can alter are:
• Lat and long These can be as retrieved from the user’s device through geolocation, or coordinates you have determined and wish to supply (perhaps to provide a map of your employer’s place of work)
• zoom This can be a value between 1 for fully zoomed out and 20 for fully zoomed in.
• mapTypeId This can be google.maps.MapTypeId.SATELLITE for a satellite map, or replace the final SATELLITE property with ROADMAP for a road map, or with HYBRID for a combined road and satellite map.
You can also use Bing maps for mapping if you prefer, but it’s a little more involved. For information on how to do so, please refer to http://tinyurl.com/bingmapsapi.
The GPS Service
The GPS (Global Positioning System) service consists of multiple satellites orbiting the earth whose positions are very precisely known. When a GPS-enabled device tunes in to these satellites, the different times at which signals from these various satellites arrive enable the device to know where it is to within just a few feet.
This is achieved by the fact that the speed of light (and radio waves) is a known constant, and the time it takes a signal to get from a satellite to a GPS device precisely indicates the satellite’s distance. By making a note of all the different times at which signals arrive from different satellites, a simple calculation lets the device derive each of the satellite’s positions relative to each other, and therefore very closely triangulate the position of the device relative to them.
Many mobile devices such as phones and tablets have GPS chips and can provide this information. But some don’t, others have them turned off, and others may be used indoors where they are shielded from the GPS satellites, and therefore cannot receive any signals. In these cases, additional techniques may be used to attempt to determine your location.
Other Location Methods
First, if your device has mobile phone hardware, it may attempt to triangulate its location by checking the timings of signals received from the various communications towers with which it can communicate (and whose positions are very precisely known). If there are a few towers, this can get almost as close to your location as GPS. But where there’s a single tower, the signal strength is used to determine a radius around the tower, and the circle it creates represents the area in which you are likely to be located. This could place you anywhere within a mile or two of your actual location, down to within a few tens of feet.
Failing that, there may be known Wi-Fi access points within range of your device whose positions are known, and since all access points have a unique identifying address called a MAC (Media Access Control) address, a reasonably good approximation of location can be obtained, perhaps to within a street or two.
And if that fails, the IP (Internet Protocol) address used by your device can be queried and used as a rough indicator of your location. Often though, this provides only the location of a major switch belonging to your Internet provider, which could be dozens or even hundreds of miles away. But at the very least, your IP address can narrow down the country, and sometimes the region you are in.
Your IP address is commonly used by media companies that restrict playback of their content by territory. However, some people are able to set up proxy servers that use a forwarding IP address in the country that is blocking them to fetch and pass content through the blockade back to their browser. Therefore, you should be aware that if you locate someone by IP address, the country identification may not necessarily be reliable.
Using geolocation will enable you to improve the features you offer to your mobile device web visitors, but not so much for desktop users, whose locations will remain difficult to ascertain.
Nevertheless, used sensibly and perhaps even in conjunction with asking your users directly to correct any such misinformation in order for you to provide better service, geolocation is a great feature. And if you know your user has an iPhone, Android, or Windows phone, you can be almost certain that you’re receiving the right data.
And that’s all there is to geolocation, so this is a short and sweet lesson, but hopefully one you have found very useful. In the next lesson I’ll take you through the extensions that HTML5 has made to HTML forms.
Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in the appendix.
1. What is the most common form of geolocation positioning hardware?
2. How can you determine whether a browser supports geolocation?
3. Which method do you call to request location data from a browser, and what values should be passed to this function?
4. If the user grants permission for you to access their location, how will that data be supplied?
5. If the user doesn’t grant permission to access their location, what information is supplied instead?
6. If you are using location data to display a Google Map, what is the URL of the API (Application Programming Interface) you should call in a <script> tag?
7. How do you pass the latitude and longitude to display to the Google Maps API?
8. What values can you supply to the Google Maps zoom property to choose the zoom level?
9. What types of Google Maps can be displayed, and how?
10. Why are IP addresses not a very accurate form of geolocation?