Home > Articles > Web Development > HTML/CSS

This chapter is from the book

Geolocation

The Geolocation API doesn't have an explicit function to ask for the user's permission to track his or her position. Instead, the browser handles this transparently for us. When the Geolocation API first requests position information from a website for which it doesn't have permission, a contextual pop-up appears to request permission from the user.

We can check to see if the browser supports the Geolocation API by checking for the following object:

navigator.geolocation

If it resolves to a non-null value, we have the ability to geolocate.

The calculated position of a user is defined by the Position object, which contains a Coordinates object named coords and a timestamp indicating when the fix was retrieved. Table 1-2 shows the properties of the coords object.

Table 1-2. Coordinates Object Properties

Property Name

Return Value

Description

latitude

double

The latitude of the position fix.

longitude

double

The longitude of the position fix.

altitude

double

The altitude of the position fix in meters. If this is unavailable, the value will be null.

accuracy

double

The margin of error of the lat-long fix in meters. If this is unavailable, the value will be null.

altitudeAccuracy

double

The margin of error of the altitude value. If this is unavailable, the value will be null.

heading

double

The direction in which the device is traveling in degrees (0° to 360°, inclusive). If this is unavailable, the value will be NaN.

speed

double

The speed in meters that the device is traveling. If this is unavailable, the value will be null.

After we have verified that geolocation is available, obtaining a position fix on a device is simple. We just call getCurrentPosition with either one, two, or three parameters, corresponding to the functions to run if getting a fix is successful, if it fails, and the options on the request, respectively.

Listing 1-5 shows the code needed to retrieve a location, draw it on a map with a marker, and draw a proximity circle around the marker.

Listing 1-5. Drawing a Map with Geolocation

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(pos) {
        var latitude = pos.coords.latitude;
        var longitude = pos.coords.longitude;

        var options = {
            position:new google.maps.LatLng(latitude, longitude)
            ,title:"Your location"};

        var marker = new google.maps.Marker(options);

        var circle = new google.maps.Circle({
            map:map, radius:pos.coords.accuracy
        });
        circle.bindTo('center', marker, 'position');

        marker.setMap(map);

        map.setCenter( new google.maps.LatLng(latitude, longitude));
    },
    function(error) {
        console.log(error.message);
    });
}

After verifying that geolocation is available, we first attempt to retrieve a fix on the position of the device. In this example, we are passing in the two parameter functions of getCurrentPosition to execute if successful, an error occurs, or if the user declines geolocation. After getting the latitude and longitude portions, we create a marker centered at that position with the title "Your location." To the marker, we attach a circle whose radius is equivalent to the accuracy of the position fix. Lastly, if there is an error, our error-handling function prints out the error message to the console. Figure 1-4 shows a sample position fix using the OpenStreetMap tile set.

Figure 1-4

Figure 1-4 Geolocation from the browser

Although we did not use it, we could have also specified an options object that indicates several preferences on the retrieved data. We could also set up a listener to execute every time there is a position change returned from the watchPosition function. Geolocation is an expensive API. Use it judiciously and don't be afraid to cache the location.

We could use geolocation to create localized leader boards, or on a multiplayer server to match players who are physically close to one another.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.