Chapter 9
Geolocation

When I was a child, my parents took me to Manhattan. While walking around, we came across a big map of the city. On the map was a big circle saying “You are here.” I clearly remember asking my parents how the map knew where we were. Many years later, I relived the moment when I realized that web sites were sending ads targeted to my location. Again, I asked how they knew where I was.

The answer to my first question is pretty obvious. The person who made the map knew where it would be placed. The answer to the second is the subject of this chapter: geolocation.

Geolocation is the process of determining where in the world a device or user is. Geolocation is useful for advertisers, developers, and the average consumer. In short, it is a very important addition to your HTML5 toolbox.

Geolocation Methods

Today, web sites can use three methods to determine your location. The original method of determining your location is through your IP address. The IP addresses of all public-facing networks and their latitude/longitude positions are stored in a database. Once a site obtains your IP address, a simple query can determine roughly where in the world you are. Depending on the quality of your device, this method can discern your location in the world within a few-meter radius.

You can try the IP method for yourself. Visit the web site www.ip2location.com to determine your location. You should see that the service likely determined your city, but not your actual location. This method is useful for advertisers to deliver ads for your area, but is of no use for developers trying to deliver turn-by-turn directions.

Another method of determining your location is through the Global Positioning System (GPS). GPS is a system of 24 satellites in earth orbit. A GPS device will send a message to these satellites. Using the time it takes to send and receive messages, your exact latitude and longitude can be determined within a few-meter radius. GPS is the ideal solution for developers who need an exact location. Most mobile devices are capable of delivering GPS information. Some systems include a built-in GPS device. However, very few desktop computers can deliver this information.

A third technique for location discovery is to triangulate based on cell tower locations. Used by most cell phones, this method returns a quick, if sometimes imprecise, location.

Luckily, HTML5 will work with whichever location method is available. The HTML5 geolocation functions can determine your latitude, longitude, and altitude. Depending on your device, it may also calculate other values, as discussed in the chapter.


TIP

Latitude is the angular distance north or south of the equator. On the globe, latitude is represented by horizontal lines. Positive values are north of the equator. Longitude is the angular distance east or west of the meridian at Greenwich, England. On a globe, longitude is represented by vertical lines. Positive values are west of Greenwich, England. HTML5 works with decimal degree values.


Privacy Concerns

Geolocation is an incredible technology; however, not everyone wants to share their location. The W3C takes your privacy very seriously. The W3C Geolocation API Specification, located at http://dev.w3.org/geo/api/spec-source.html, contains strong language protecting the consumer. Specifically, a site will not gather the location information for a device until the user approves.

The W3C specification requires the permission request to include the name of the site requesting the permission and clear responses. Figure 9-1 shows the Google Chrome permission popup. Not shown in the figure is a link to more information regarding the service.

image

Figure 9-1 Chrome asking for permission to share your location

The API provides a method for the developer to track the current location of an object. However, to protect the user, the method must be in an active browser session. Since the session must be active, the user cannot unknowingly be tracked using HTML5.

Depending on the browser you choose, you can change your mind regarding sharing your location. Google Chrome places an icon in the address bar that allows you to change the share settings, as shown in Figure 9-2. In Firefox, you need to select Tools | Page Info | Permissions to bring up the dialog shown in Figure 9-3.

image

Figure 9-2 Setting Chrome location-sharing options

image

Figure 9-3 Setting Firefox location-sharing permissions

As a developer, you need to respect your users’ rights to privacy. If they deny your request, no matter how benign it seems to you, the session is over. Later in the chapter, you will see how to graciously respond to errors in acquiring location information.

Finding Your Location

Tracking your user’s location is handled through a new property of the JavaScript navigator object. JavaScript’s navigator is the perfect choice, as this is the object on the device that is requesting the location. The new navigator property is geolocation.


TIP

The examples in this chapter work better from a web site rather than locally. I suggest running them from www.webbingways.com or www.mhprofessional.com/computingdownload or a server that you control.


The geolocation property contains very few methods. Currently, only the following three methods are supported (each function is named well):

image The getCurrentPosition method attempts to retrieve the current position of the object.

image The watchPosition method updates the page as the device moves, effectively tracking the device’s movements.

image The clearWatch method stops watchPosition from tracking the device.

To start the process of getting a user’s location, you need to begin with getCurrentPosition or watchPosition. Both will request the location from the device but will not do anything with the information.

Code Listing 9-1 shows the beginning of a program that will display your latitude and longitude. The function findYou calls navigator.geolocation. getCurrentPosition(). This initiates the request for location information.

Code Listing 9-1 The request for your location

image

This code does not do anything exciting. It merely requests the location from the device. The browser will ask if you wish to share the location. Once you respond, nothing else happens. We are going to expand on this code, to display your latitude and longitude.


NOTE

Your computer will respond to this code immediately. Your smart phone will need to have location sharing enabled. On my Android phone, this was done via the menu option Settings | Location and Security | Use Wireless Networks.


The getCurrentPosition function takes zero to three parameters, as follows:

image Calling getCurrentPosition without any parameters is used to validate that the browser and device support geolocation.

image The first parameter is the name of an asynchronous callback function that will handle the location information. This function must accept a parameter of type Position.

image The second parameter is a name of a callback function that should handle errors.

image The third parameter lists the position options, which change how the device gathers the location. Table 9-1 lists the position options.

image

Table 9-1 Position Options for getCurrentPosition

The position options are passed into the getCurrentPosition function set inside a set of curly braces ({}). The value is set as variableName :value. The syntax is shown here:

image

Code Listing 9-2 shows a complete call to getCurrentPosition. Sample output is shown in Figure 9-4. The function showPosition will display the detected latitude and longitude in paragraphs. Function noLocation is the error function. Finally, maximumAge is set to 20 minutes, and timeout is set to 30 seconds.

image

Figure 9-4 Location information displayed in Firefox

Code Listing 9-2 A working location-aware web page

image

image

The function showLocation has all of the action in this page. It accepts the parameter location of type Position, which has several properties, as listed in Table 9-2. Of these properties, only latitude, longitude, accuracy, and timestamp are guaranteed to be present. The others are device-dependent. The latitude, longitude, and accuracy properties are written into the paragraphs with identifiers (ids) in the body.

image

Table 9-2 Properties of Type Position

The accuracy of this page will vary greatly, depending on several factors. In testing, my home Internet connection responded with less than 200 meters of accuracy. The latitude and longitude were actually in my neighbor’s swimming pool! At work, the accuracy was more than 42,000 meters. The latitude and longitude were in a different neighborhood of the city. Mobile devices responded differently, depending on the brand and location options set.

Handling Rejection and Errors

Retrieving a user’s location is not guaranteed. Several errors can occur:

image Recall that sending a location is optional. The user can decide to not share.

image The position may be currently unavailable.

image The device may take too long to respond.

Your code should gracefully respond to these conditions.


NOTE

Demonstrating location-retrieval errors is easiest in Google Chrome.


As noted earlier, the second parameter to getCurrentPosition is the error callback function. This function accepts a parameter of type PositionError. PositionError contains one property code, which is a number that describes the error type. Each of the possible errors is defined as a constant in the PositionError class. The possible errors are PERMISSION_DENIED, POSITION_UNAVAILABLE, and TIMEOUT.

Code Listing 9-3 improves on the noLocation function with a switch statement that prints an error message to the user.

Code Listing 9-3 A useful error response

image

image

image

Code Listing 9-3 does respond to a user’s error; however, it is up to the user to refresh the page. An improvement on this code would be to default to a location or recall the getCurrentPosition.

Figure 9-5 shows the output from a denied request. Notice two things:

image The message is displayed on the screen.

image The location icon in the toolbar has a red x, indicating that the user chose not to share.

image

Figure 9-5 Denied response to a location request

Detecting Browser Support

The code in the previous section assumed that your browser handles HTML5 geolocation. As of this writing, the most recent versions of Chrome, Firefox, and Internet Explorer 9 support geolocation. Additionally, every Android and iPhone I tried supported my pages. However, you should prepare for users still using outdated browsers.


TIP

Google offers a service called Gears (http://gears.google.com). This JavaScript API allows you to use HTML5 geolocation on browsers that do not support the technology.


As justification, consider W3Schools.com. This site delivers tutorials and training on web technologies. Its visitors tend to be on the geeky side. Their own stats report that about 26% of the visitors use Internet Explorer. Only 3.6% used Internet Explorer 9. Users visited with versions of Internet Explorer dating back to version 6! If you were to look at the browser usage for sites such as Google or Yahoo, you would find that the percentage of Internet Explorer usage nearly doubles.


TIP

To see current browser usage stats, visit www.w3schools.com/browsers/browsers_stats.asp.


So, if browsers are free, why are people still using outdated browsers? The reasons range from ignorance to serious business needs. For example, a pharmaceutical company in my hometown is still using Internet Explorer 6 on all of its Windows computers. The reason is that many of their internal databases are powered using web pages written with technologies that work only on that version. Rewriting these web sites is a huge undertaking. Thus, Internet Explorer 6 is required for the company to stay in business.

Detecting if a browser supports geolocation is simple. If support exists, navigator .geolocation returns a value that JavaScript converts to a Boolean value:true if the browser supports geolocation or false if it does not. Simply place an if statement around the call to navigation.geolocation. Use the else clause to display an error message. Code Listing 9-4 shows the modification needed to detect browser support.


NOTE

The detection trick for geolocation in Code Listing 9-4 really does not return a Boolean value. Instead, we are depending on JavaScript’s weak typing.


Code Listing 9-4 Detecting browser support

image

image

Mapping Your Place in the World

Geolocation as presented so far in the chapter is not very exciting. The example in this section demonstrates the use of the Google Maps API. This service, which is free to individuals and sites that do not charge for their services, allows you to easily add a map to your site.


TIP

Google, as usual, provides excellent documentation and tutorials. For details, visit http://code.google.com/apis/maps/index.html.


Figure 9-6 shows the results of a Google Map call. To create a simple map like this on your web page, you will need to peform several steps.

image

Figure 9-6 The result of a Google Map call

The first step is to create a div section on your page named map and style it appropriately. Next, add the Google Maps API to your project. The Google Maps API loads the Map code for use on the web page. It also tells Google whether you have a device with a GPS sensor. The following snippet shows the loading for a device without a GPS sensor. If you have a sensor, change the false to true.

image

Once the API is loaded, you can begin to create your map. In your showPosition function, create a variable called position that instantiates a variable of type google. maps.LatLng. Pass into the constructor your latitude and longitude values. The following snippet shows map creation.

image

Now you need to set the options for this map. You have many choices, including these three basic options:

image The zoom level, which ranges from 0 to 20. A 0 value is basically the view from space;

20 is as close as you can get.

image The center position, which is the LatLng variable that sits in the center of the map.

image The map style, which changes the map. Table 9-3 details the choices. I encourage you to experiment with the styles.

image

Table 9-3 Basic Google Map Styles

The following code snippet shows the setting of map options.

image

The last step is to actually draw the map. As with the latitude and longitude information, you draw the map into an object referenced by the getElementById function. Code Listing 9-5 shows the code for drawing a map, with the error code removed for brevity. The complete code is available on www.webbingways.com or www.mhprofessional.com/computingdownload.

Code Listing 9-5 Drawing a map

image

image

image

image

Getting on the Map

The sample map is pretty plain. It needs markers showing important places. This is defined as geocoding. To geocode, you need to instantiate LatLng objects with the coordinates of your objects. Figure 9-7 shows locations of earth’s natural wonders placed on a Google map. Notice that most of the icons are the familiar Google-placed teardrop. However, I changed the icon over my house.

image

Figure 9-7 Locations placed on the map

The google.maps.Marker API provides the functionality to place icons on the map at specified latitude and longitude locations. You are able to provide additional metadata, such as a custom icon and a title. The title is available when you hover over the icon. For details on additional properties, consult with the Google documentation.


TIP

Thanks to openstreetmap.org for providing an easy-to-use interface that gives very close latitude and longitude values.


Geocoding a location requires two items: the latitude and longitude of a location you wish to plot, and a map object. In your code, after the creation of the map object, you will instantiate an object of type google.maps.Marker. The metadata is passed in as options, similarly to how you built the map.

Code Listing 9-6 shows a specific example for my house and the Grand Canyon. The complete code is available on www.webbingways.com or www.mhprofessional.com/computingdownload, in the Chapter 9 link.

Code Listing 9-6 Geocoding locations

image

Continuously Tracking Movement

The function getCurrentPosition allows developers to acquire a device’s location on demand. However, HTML5 offers the ability to update your location as it changes, in real time. For this feature, instead of using getCurrentPosition, you use watchPosition.

The watchPosition method takes the same parameters as getCurrentPosition. However, whenever the device detects a change in location, the showLocation function will be called. Your job as the developer is to handle what to do with this information.

The call to watchPosition returns a unique identifier for the watch operation. This identifier can be used to cancel the track later with the clearWatch function.

Code Listing 9-7 shows watchPosition in action. This code will create a new table row whenever the device’s position updates. I added the timestamp for proof that the page is updating. Figure 9-8 shows an example of the results. This code will probably not work well on your computer, but it works great on a smartphone. The complete code is at www.webbingways.com or www.mhprofessional.com/computingdownload.

image

Figure 9-8 Tracking a user’s location

Code Listing 9-7 Tracking your locations

image

image

image

Summary

HTML5 allows you to build a location-aware web page. Using the new features of navigator.geolocation, you can quickly determine user location. For example, the getCurrentPosition method allows you to retrieve the latitude and longitude of your end user.

Of course, tracking offline locations brings up some privacy worries, and thus geolocation technology is completely dependent on user acceptance. HTML5 will not track users without their express permission.

While HTML5 Geolocation APIs are useful to determine location, adding the Google Maps API to the mix brings the technology to life. With a very few lines of code, you can render a fully interactive Google map in a div on the screen and also place icons at desired locations.

In the final section of this chapter, you learned how to track the movements of a device with the navigator.geolocation.watchPosition method.

The use of this geolocation technology will grow in the coming years as advertisers and developers dream up new ways of using your location data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.255.36