Getting a One-Time Position

Getting the position of the user is simple enough; just call navigator.geolocation.getCurrentPosition with a callback. This triggers a notification at the top of the browser, as shown in Figure 23-1, giving the user the power to allow or deny the request. If you supply a second callback, that callback is called if the browser couldn’t get the location due to a denied request or other error.

Figure 23-1: The geolocation permission dialog.

c23f001.tif

To see the data in the console that’s returned from a request, you can enter the code in Listing 23-1 into a file called position.html, load the page in a desktop browser, and open up the JavaScript console.

Listing 23-1: Getting a one-time position

<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Grabbing the position</title>
</head>
<body>
  <script>
    function logPosition(position) {
      console.log(position);
    }
    function positionError(error) {
      console.log(error);
    }
    navigator.geolocation.getCurrentPosition(logPosition,positionError);
  </script>
</body>
</html>

Examining the console shows you the result of the request. If you denied the request or the system couldn’t look up your location, the positionError method is called with a PositionError object. If you run this from a file:// URL, Chrome will give you an error by default so you’ll want to run it from localhost.

If the geolocation was successful, ...

Get Professional HTML5 Mobile Game Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.