Chapter 8. Geolocation

Christopher Deutsch

Marc Grabanski

Introduction

The W3C Geolocation API allows for scripted access to geographical location information associated with a device’s browser. In this chapter we’ll first cover how to access this API and then dive into some examples of what you can do with this data using Google Maps and other third-party libraries like SimpleGeo.

All of the examples in this chapter use jQuery (see http://jquery.com), which can easily be included using a script tag in one of two ways. There is no need to download the jquery.js file; your web page can use the version hosted on Google’s Content Delivery Network (CDN):

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>

And, just in case a call to the file across the Internet isn’t available, a fallback to a local copy of the jQuery file can come right afterward in a second script element that checks for the previous copy’s successful inclusion:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script>window.jQuery || document.write("<script
    src='js/libs/jquery-1.6.4.min.js'>\x3C/script>")</script>

8.1. Getting Basic Geolocation Data

Problem

You want to find the location of the user’s Internet device.

Solution

Use the new HTML5 Geolocation API to get the user’s location when she clicks a button and output the values to the web page, as shown in Figure 8-1.

Figure 8-1. The latitude and longitude coordinates determined natively through the browser

Start by ...

Get HTML5 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.