HTML5 New Feature Series: Geolocation

Today handheld devices are so popularly spreading over our around, and the position feature plays an vital role in the applications developed for these devices. Some applications, such as Uber, can find the nearest car for you by your current position, and the group-buying application can recommend the theater and food nearby for you via your position information, also, map application can make an optimal road map for you by your current position and help you get to the destination, we can say that, position information is definitely essential for mobile application.
And to follow this trend, HTML5 provides us the Geolocation library, with this feature we are able to build an application in which we can easily implement the functionalities that we mentioned above. Then today I will show you the whole landscape of this feature.
First of all, we can obtain a Geolocation instance via geolocation property of navigator:
HTML5 New Feature Series: Geolocation_第1张图片
And there are three common-used methods below showing:

getCurrentPosition: to get current position
watchPosition: to trace position changes
clearWatch: cancel the watch operation above

We will take a look at the getCurrentPosition method in the first place, the following is its signature:

navigator.geolocation.getCurrentPosition(success[, error[, options]]);

The first parameter is a success handler, and the second is error handler, the third one is an optional configure for function’s running. Now we attempt to call this function:

navigator.geolocation.getCurrentPosition(function(position) {
    //success handler code goes here
    console.log(position);
}, function(error) {
    //error handler code goes here
    console.log(error);
}, {//options
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
});

Once the code is running, there will be a confirm dialog coming out to request the permission for locating:
HTML5 New Feature Series: Geolocation_第2张图片
If we click Allow button, that means we permit the program to locate, and success handler will be triggered after the position information is returned, we printed the position in the console:
HTML5 New Feature Series: Geolocation_第3张图片
We can see that position is actually a Geoposition instance which contains coords and timestamp two properties, and the latter is a timestamp when position data is obtained, also, there are several position relevant properties included in coords:

accuracy: the accuracy measured in meters
altitude: the altitude measured in meters, if no height sensor provides data for browser, this value will be null
altitudeAccuracy: the altitude accuracy measured in meters, likewise, this property will be set to null if no height data provided
speed: the speed of device’s moving, measured in m/s, if no data can get from device, this value will be null
heading: the current moving direction, measured in degrees, [0 ,360), indicates how far off from true north by clockwise, 0 represents true north, 90 is true east, and 180 indicates true south, 270 means true west. Note that if speed is 0, heading will be NaN, and if device is not able to provide direction data, this property value will be null
longitude: longitude expressed in decimal
latitude: latitude expressed in decimal

We will receive these data in success handler, and do next processing according to actual device and application scenario.
Go back previous confirm dialog, if we click the Block, it will fail to request permission, accordingly, the error handler will be invoked, and an error object will be passed in this handler, the following is the error object we print in console:
HTML5 New Feature Series: Geolocation_第4张图片
We can see that error is an instance of PositionError, it includes code and messageproperties, representing error type and error message separately, thereinto, there are three error types:

1: PERMISSION_DENIED - failed to request permission due to user’s rejection
2: POSITION_UNAVAILABLE - failed to get position caused by an internal error
3: TIMEOUT - didn’t get position data after running out the time we configured

That’s the error handler above, commonly if an error occurred when getting position, we need to capture it and handle with it properly to get better experience, it’s very important.
In the invocation of getCurrentPosition, we also provide the third parameter, just a simple object which contains a few of configurations, they are specified to config the runtime arguments for this function:

enableHighAccuracy: by default, it’s a false value, and if specified as true, that means it’s required to get the data as accurate as it can under the condition of supported by device, but it will lead to certain consumption in battery and time.
timeout: the timeout measured in milliseconds, indicates to stop the operation after running out the time, the default is Infinity
maximumAge: to specify a longest time to cache the position data, during this period, it will obtain the data from cache when attempting to get position, it’s measured in milliseconds.

Above is all about getCurrentPosition, in some cases such as map navigation, we need the latest position to plan a new road map for user, and apparently getting data once is not able to meet our requirement, therefore, we need the watchPosition method:

watchId = navigator.geolocation.watchPosition(success[, error[, options]]);

watchPosition method is similar with getCurrentPosition, the only difference is that success will be running repeatedly, once got the latest data, success will be triggered again, similarly, the error will also execute repeatedly if it failed to get up-to-date position serially.
We may notice that a watchId is returned in the signature, it indicates the current ID of watch operation, and we can clear this operation by calling the clearWatch function with this watchId after tracing position is done:

navigator.geolocation.clearWatch(watchId);

That’s the introduction of the common-used three APIs regarding Geolocation, we can choose appropriate method according to the actual situation to get user’s position.
Although Geolocation has been supported by the majority of browsers, in order to take care of the browser in low version, we still need to detect if it supports:

if ('geolocation' in navigator) {
  // getting usr's position
} else {
  // tips: your position is not available
}

At last we will illustrate how it works in real development with a simple program:

var API = {
    //get recommended data by current longitude and latitude
    getSurroundingRecommendations: function(longitude, latitude, callback) {
        //simulate data obtaining from server.
        setTimeout(function() {
            var data = [
                {
                    //item
                },
                {
                    //item
                }
            ];
            callback(data);
        }, 500);
    }
};

document.addEventListener('DOMContentLoaded', function() {
    //detect if Geolocation is supported
    if (!'geolocation' in navigator) {
        console.log('Geolocation is not supported in your browser');
        return;
    }

    var successHandler = function(position) {
        var coords = position.coords,
            longitude = coords.longitude,
            latitude = coords.latitude;

        API.getSurroundingRecommendations(longitude, latitude, function(data) {
            console.log(data);
        });
    },
    errorHandler = function(error) {
        console.log(error.code, error.message);
    },
    options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
    };

    navigator.geolocation.getCurrentPosition(successHandler, errorHandler, options);

}, false);

In the code, we firstly define a method to get the recommended data by user’s position, and then after the DOM is loaded, we start to get current position data and call this method to obtain mock data, note that, we will do further operations with the data in real development.
That’s all about it, thanks.

你可能感兴趣的:(html5,geolocation)