Geolocation

Although 3D graphics are awesome, as is a socket-based, multiplayer game, neither technology is necessarily new. Geolocation, on the other hand, is somewhat of a more recent phenomenon. With it, we are able to use JavaScript to determine the physical location (geographical location) of a user. Having such a tool at our disposal opens up new possibilities of awesome, highly innovative game concepts.

Now, whenever a new feature comes out that promises to be able to track down exactly where a user is physically located, most people (except for developers, of course) get at least a little scared about it. After all, how creepy would it be to play a very dark, survival horror game, knowing that other people playing the game can see exactly where you live. Luckily for us, the entire geolocation API is opt-in-based, meaning that the user is prompted about the application attempting to capture the user's location and the browser only allows the application to continue to capture the GPS location of the user if and when the user accepts the request from the application.

As shown in the following screenshot, when attempting to use the geolocation API, the browser will somehow alert the user about it and ask for permission to continue. If the user decides not to share his or her location with the application, the browser will not share the location with the application.

Geolocation

Although each browser implements this request step slightly differently, especially with regards to how this notification and request is graphically conveyed to the user, there is no way for the application to use the geolocation API to forcefully or secretly collect this piece of information.

function getGeo(position) {
  var geo = document.createElement("ul");
  var lat = document.createElement("li");
  var lon = document.createElement("li");

  lat.textContent = "Latitude: " + position.coords.latitude;
  lon.textContent = "Longitude: " + position.coords.longitude;

  geo.appendChild(lat);
  geo.appendChild(lon);
  document.body.appendChild(geo);
}

function doOnPermissionDenied(message) {
  var p = document.createElement("p");

  p.textContent = "Permission Denied Error: " + message;
  document.body.appendChild(p);
}

function doOnPositionUnavailable(message) {
  var p = document.createElement("p");

  p.textContent = "Position Unavailable Error: " + message;
  document.body.appendChild(p);
}

function doOnTimeout(message) {
  var p = document.createElement("p");

  p.textContent = "Operation Timeout Error: " + message;
  document.body.appendChild(p);
}

function doNoGeo(positionError) {
  switch (positionError.code) {
    case positionError.PERMISSION_DENIED:
      doOnPermissionDenied(positionError.message);
      break;

    case positionError.POSITION_UNAVAILABLE:
      doOnPositionUnavailable(positionError.message);
      break;

    case positionError.TIMEOUT:
      doOnTimeout(positionError.message);
      break;
  }
}

// Ask the user if you may use Geolocation
navigator.geolocation.getCurrentPosition(getGeo, doNoGeo);

The first part of the API involves asking the user for permission to get his or her location. This is done by calling the getCurrentPosition function on the geolocation attribute of the global navigator object. The function takes two arguments, namely a callback function to be called if the user allows the browser to share the user's location and a callback function to be called if the user denies the application's request.

If the user accepts the request from the application to share the geolocation, the callback is invoked with a Geoposition object passed in to it. This object has nine properties that we can use:

  • timestamp: When the callback function was invoked
  • coords: An instance of class Coordinates
  • accuracy: How accurate the GPS coordinate is (in meters)
  • altitude: In meters
  • altitudeAccuracy: How accurate the altitude is (in meters)
  • heading: In degrees clockwise from north
  • latitude: As a double
  • longitude: As a double
  • speed: In meters per second

There are only three attributes in the position object that are required to be present. These are the latitude and longitude values, along with the accuracy attribute. All other values are optional and will be available if the hardware in use supports them. Keep in mind, also, that this feature is equally available on mobile devices, so it is possible and likely that the user's position changes somewhat during the course of the application's usage. Thankfully, once the user has agreed to have his or her position shared with the application, any subsequent calls to get the current position will be successful right away. Of course, the user can just as well clear the permissions for a given domain right from the browser, so any subsequent calls to get the position may fail (if the user has disabled the feature altogether) or result in a new request for permission (in case the user simply cleared the permissions cache on the browser).

As you can see from the following screenshot, Google Chrome displays a different icon on the address bar when a page is using geolocation to let the user know about it. By clicking this special icon, the user can reset the permissions, or block or allow the application on a more long term basis.

Geolocation

A Google Maps example

Possibly the most common use case for geolocation these days involves rendering a position to a map. Thankfully, Google offers a terrific, free API that we can tap into for the purposes of doing just that. With this mapping service, we can capture a user's geolocation, then render a marker on the map right where the user is located (or somewhere within the accuracy distance of where the user is). While the Google Maps API is rather robust, we will simply cover a fairly trivial example of how we can go about obtaining the user's location then render that coordinate point on a map.

The general idea where the maps API is based is simple: create a map object to be rendered inside some HTML container object, specify where this map is to be centered (so that we can know the general area within the map that is immediately visible to the user), and add markers to it. Marker objects take at least two attributes, namely a reference to a map object and a GPS coordinate point. In our example, we'll center the map on the user's GPS coordinate and also place a marker on that same location.

// Step 1: Request permission to get the user's location
function initGeo() {
  navigator.geolocation.getCurrentPosition(renderToMap, doNoGeo);
}

// Step 2: Render the user's location on a map
function renderToMap(position) {
  var container = document.createElement("div");
  container.id = "myContaier";
  container.style.width = window.innerWidth + "px";
  container.style.height = window.innerHeight + "px";

  document.body.appendChild(container);

  // Define some point based on a GPS coordinate
  var coords = new google.maps.LatLng(
    position.coords.latitude,
    position.coords.longitude);

  // Specify how we want the map to look
  var options = {
    zoom: 16,
    center: coords,
    mapTypeControl: false,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // Create a map, and inject it into the DOM element referenced
  var map = new google.maps.Map(container, options);

  // Create a marker and associate it with our map
  var marker = new google.maps.Marker({
    position: coords,
    map: map,
    title: "Where's me?"
  });
}

While the preceding example might not be the most exciting piece of software you've seen, it does a great job illustrating two powerful points. First, the geolocation API is powerful, yet, it is also possibly the easiest of all other HTML5 APIs in terms of all the functionality it offers and everything you need to know in order to use it. Second, the preceding snippet shows how open the web platform is and how much we can potentially accomplish simply by taking advantage of other people's work.

Running the preceding code will result in a very nice looking map covering the entirety of the screen, with the central point of the map being the user's current location, as shown in the following screenshot. Keep in mind that Google Maps is just one example of the many free APIs that we can use in conjunction with such powerful HTML5 features as geolocation.

A Google Maps example
..................Content has been hidden....................

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