How to use the W3C Geolocation API

By Shwetank Dixit

Introduction

Imagine visiting a city for the first time. You're hungry, but don't know where the nearest restaurants are and which of them are any good. Wouldn't it be nice if some app could detect your location and provide you with a list of restaurants closest to you, along with reviews and ratings for each one?

And this is not the only consideration — could it detect your location accurately, keeping in mind your privacy as well? This is where the W3C Geolocation API comes in, support for which is included in Opera 10.60 and above.

What is Geolocation?

By Geolocation, we mean the use of scripts within the browser to determine where a particular user is. This will have countless advantages in Web applications and is an exciting capability for browsers to have. For example, you could build a Web service to provide you with information about the nearest hospital, with turn-by-turn route navigation info. Or, how about an app that tells you about all the cool meetups happening in your area in the coming days, along with exact locations? Excited yet? Read on!

The W3C Geolocation API

People have been trying to determine a user's location for quite a while on the Web. However, most of the older methods are quite inaccurate, and don't seek the user's permission to access this information. The W3C Geolocation API is specified by the W3C to provide a uniform way for developers to make location-aware Web applications. It is much more accurate and built in such a way that the user is able to control whether his or her location information is to be revealed on a given site or not.

How is location determined?

In browsers that support Geolocation, user locations are determined based on a combination of data from users' wifi access points and users' IP addresses.

How will visitors to your site approve or deny sharing of their location information?

Image of browser requesting user permission for sharing of location information

Figure 1: A browser alerting the user that an application is trying to access their location data via the Geolocation API and asking for their permission to access it.

Whenever you access a page that includes Geolocation code, a small notification will appear at top of the page asking whether you want to share your location information with the application or not (see Figure 1). If you do, then the information will be shared; you can also choose to select remember my choice for this site so that in future you won't be asked again and the application will automatically go with the choice you made the first time. Similarly, you can block your location information, giving you as the user a case-by-case choice in terms of your privacy.

How do you use it in a Web app?

Using the Geolocation API is easy. First, you'll want to determine whether the user's browser actually supports Geolocation. You can do this with JavaScript to query the browser and see if it supports the navigator.geolocation property. For a one-shot determination of the user's location, you can use the navigator.geolocation.getCurrentPosition() function which, if successful, will call whichever success callback function you choose.

A good way to do this is:

//Check if browser supports W3C Geolocation API
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

In a production system, you should consider fallback so those users without Geolocation-enabled browsers can manually enter their location by inputting their postal code or choosing their position on a map, for example.

Then you add the success function:

function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;
    alert('Your latitude is :'+lat+' and longitude is '+long);
}

You can write the error function however you want. Refer to the PositionError Interface in the specification for more on error codes. For the sake of the example, we'll keep it simple for now:

function errorFunction(position) {
    alert('Error!');
}

Here is the resulting example page.

If you want to keep watching the user's position and update the function accordingly, you can use the navigator.geolocation.watchPosition() function. It accepts the same parameters and works in more or less the same way as getCurrentPosition(). In both getCurrentPosisition() and watchPosition(), only the first parameter is necessary. The second parameter, which handles the error callback, is optional. In addition to that there is a third optional parameter — an object containing attributes that define:

  • greater accuracy
  • timeout between determination of location and invocation of the success callback function.
  • A maximum age for which the app can cache the location information until the next getCurrentPosition() or watchPosition() is called.

What next?

Having the ability to determine the user's location is great. However, with the API you get a latitude/longitude pair. How do you get to know where on earth that latitude/longitude pair corresponds to? That is where reverse geocoding comes into play.

Reverse geocoding is the process of finding out where exactly a latitude/longitude pair corresponds to. For example, if we are given a lat/long pair of (38.898748, -77.037684), reverse geocoding can tell us that it corresponds to the White House in Washington, D.C.

There are a few ways to do reverse geocoding and all of them require using some external service or other. You can use GeoNames.org's API to do it, as well as WikiMapia's API or Data Set called Nominatim, run by volunteers. Google Maps also provides a way to reverse geocode latitude/longitude pairs into actual addresses to display on a map.

Other APIs in which latitude/longitude pairs can be used include the Flickr API, which includes methods for retrieving photos taken at a particular latitude/longitude pair, the Meetup.com API, and others.

Finding you on a map

Let's quickly go through a small example that uses Google Maps to display the map of the place where the user is currently located. We'll first include the script to load Google Maps onto the page:

<script src="http://maps.google.com/maps/api/js?sensor=false"></script>

Then we include our logic to determine the location and display a map centered on that location:

<script type="text/javascript">
// Determine support for Geolocation
if (navigator.geolocation) {
    // Locate position
    navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
    alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.');
}

// Success callback function
function displayPosition(pos) {
    var mylat = pos.coords.latitude;
    var mylong = pos.coords.longitude;
    var thediv = document.getElementById('locationinfo');
    thediv.innerHTML = '<p>Your longitude is :' +
        mylong + ' and your latitide is ' + mylat + '</p>';

//Load Google Map
var latlng = new google.maps.LatLng(mylat, mylong);
    var myOptions = {
      zoom: 15,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
   
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

//Add marker
var marker = new google.maps.Marker({
	     position: latlng, 
	     map: map, 
	     title:"You are here"
	 });
}

// Error callback function
function errorFunction(pos) {
    alert('Error!');
}
</script>

Finally, the HTML and CSS to display the data is as follows:

<head>
    <style type="text/css">
        html, body {
        width: 100%;
        height: 100%;
    }
    #map_canvas {
        height: 85%;
        width: 100%;
    }
    </style>
</head>
<body>
    <div id="map_canvas"></div>
    <div id="locationinfo"></div>
</body>

Figure 2 shows the resulting Geolocation example. It will ask you for permission to share your location and then display a Google Map of your location.

Screenshot of the article mentioned above

Figure 2: Screenshot of the page, which shows your co-ordinates and a map centered on those co-ordinates.

In the above screenshot, you may notice a small icon representing geolocation on the right side of the address bar. This icon will be on any page in which geolocation is being used. If you deny geolocation privileges to a page which requests it, then this icon will not appear on the address bar of that tab. Click on the icon to access further settings related to geolocation, such as denying a page access to your location.

Conclusion

The W3C Geolocation API provides an exciting and convenient way for Web developers to allow their applications to make use of the user's location. The capability to do it is more accurate now than past methods and provides a greater level of privacy to users than ever before. Now it's up to developers to make exciting applications that build upon this capability.

Demo Pages

Read more...

This article is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported license.

Comments

The forum archive of this article is still available on My Opera.

No new comments accepted.