HTML5 Geolocation API

Later we will rewrite the weather widget once again to get the weather from a web service instead of a static file on the server. We want to show the user the weather for their current location, so we need some way to determine where the user is. HTML5 has just the thing for that: the Geolocation API.

Geolocation is widely supported by nearly every modern browser. The accuracy of the location depends on the capabilities of the user's device. Devices that have GPS will give you a very accurate location, while those that don't will try to determine the user's location as close as they can by some other means, such as by IP address.

The Geolocation API is accessed by using the navigator.geolocation object. To get the user's location you call the getCurrentPosition() method. It takes two parameters- a callback function if it succeeds and a callback function if it fails:

navigator.geolocation.getCurrentPosition(
    function(position) { alert("call was successful"); },
    function(error) { alert("call failed"); }
);

The function that is called on success gets an object passed into it that contains another object named coords. The following is a list of some of the more useful fields the coords object contains:

  • latitude: This is the user's latitude in decimal degrees (for example, 44.6770429).
  • longitude: This is the user's longitude in decimal degrees (for example, -85.60261659).
  • accuracy: This is the accuracy of the position in meters.
  • speed: This is the speed the user is moving in meters per second. This is available for devices with GPS.
  • heading: This is the heading degrees that the user is moving in. Like speed this is for devices with GPS.

For example, if you wanted to get the user's location you would do the following:

var loc = position.coords.latitude + ", " + position.coords.longitude);

The user must allow your page to use the Geolocation API. If they reject your request, the call to getCurrentPosition() will fail, and depending on the browser your error handler may get called or fail silently. This is what the request looks like in Chrome:

HTML5 Geolocation API

The error handler gets passed an error object that contains two fields, code and message. The code field is an integer error code and message is the error message string. There are three possible error codes: permission denied, position unavailable, or timeout.

The Geolocation API also has a watchPosition() method. It works the same as getCurrentPosition(), except that your callback function gets called whenever the user moves. This way you can track the user and update their position in your application in real time.

Note

In some browsers you must be running the web page through a web server such as IIS or Apache for geolocation to work.

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

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