7. Geolocation

The Geolocation API was removed from the core of the HTML5 specification and is, according to the W3C nomenclature, just in its early stages. But it is already largely implemented, particularly in mobile browsers. One reason for the rapid implementation is most likely because the interface is short and abstract: Only three JavaScript calls cover the whole range of functions. The specification does not state how the browser has to determine locations, only the format in which the result should be returned.

After a brief introduction regarding the nature of geographical data, we will demonstrate the new functions using several brief examples. If you try our examples on a smartphone, you will quickly experience that Aha! Effect.

7.1 Introduction to Geolocation

This section introduces you to the basics of geolocation. It covers geographical data and online map services.

7.1.1 About Geographical Data

You may already have come across a coordinate in the format N47 16 06.6 E11 23 35.9. The position is specified in degrees-minutes-seconds. In this example, the desired location is at a latitude of 47 degrees, 16 minutes, and 6.6 seconds north, and a longitude of 11 degrees, 23 minutes, and 35.9 seconds east. These kinds of coordinates are referred to as geographical coordinates. Unfortunately, the great drawback with these values is that they are very difficult to calculate with, not just because we are used to thinking in decimal numbers. Because the coordinates specify a position on the spheroid Earth, the curvature of the planet’s surface has to be taken into account when calculating distances.

To simplify the situation, projected coordinates are used in practice. The spheroid Earth is divided into strips where the linear distance between points can be measured. Many countries use their own coordinate system, adapted to local requirements. In Austria, for example, data is referenced in the Bundesmeldenetz, a Cartesian coordinate system. All common coordinate systems have a numeric identifier, the EPSG code (administrated by the European Petroleum Survey Group).

Obviously, the Geolocation API cannot take into account every existing coordinate system. The x and y coordinates are therefore not projected but are specified in geographical coordinates in decimal degrees. The standard specifies the widely used World Geodetic System 1984 (WGS84) as a geodetic reference system. It basically describes the underlying reference ellipsoid. The y value is specified in meters above this ellipsoid. Any point on or near Earth can be described with sufficient accuracy using this system.

7.1.2 Online Map Services

To represent geographical data in a browser, you have several options: SVG is very well suited due to its flexible coordinate system, and data can be drawn as a raster image using canvas. The easiest solution is to use an existing JavaScript library. Of the free libraries available online, we will look closer at Google Maps and OpenStreetMap. Microsoft’s map service Bing Maps can only be used after registering, so we will not discuss it here.

The two libraries introduced in this chapter use a mixture of raster and vector data for display. To enable faster loading times, the raster images are subdivided into tiles and calculated in advance for all zoom levels, allowing for step-by-step image construction. Vector information is displayed, depending on the browser, in SVG or in the Microsoft specific VML format for Internet Explorer.

7.1.2.1 Google Maps

Google Maps is undoubtedly the most widely used map service on the Internet. Many companies use the free service to cartographically represent their location. But Google Maps can do much more than place position markers on a map. As you can see from the website http://maps.google.com/help/maps/casestudies, more than 150,000 websites use Google Maps, including large companies, such as the New York Times.

The library’s current version, V3, is very different from earlier versions: To use it, you no longer need an API key (so registration with Google is not required), and the library was optimized for use on mobile devices. As is so often the case with Google products, programming is very straightforward. For a simple road map of Central Europe, you need only a few lines of HTML and JavaScript, as shown in Listing 7.1:

Listing 7.1 Road map of Central Europe with Google Maps


<html>
 <head>
 <script type="text/javascript"
  src="http://maps.google.com/maps/api/js?sensor=true">
 </script>
 <script type="text/javascript">
  window.onload = function() {
    var map =
      new google.maps.Map(document.getElementById("map"),
        { center: new google.maps.LatLng(47,11),
          zoom: 7,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    );
  }
 </script>
 <body>
  <div id="map" style="width:100%; height:100%"></div>


When loading the library, you must specify the sensors parameter. If it is set to true, the device can determine its position and inform the application. This is particularly useful for mobile devices (such as smartphones with GPS). Once the entire page is loaded (window.onload), a new object with the type google.maps.Map is created, whose constructor receives as its first parameter the HTML element provided for displaying the map. The second parameter determines a list of options of what is displayed on the map and how. In this case, the center of the map is set to 47 degrees north and 11 degrees east with a zoom level of 7 (zoom level 0 is equivalent to a view of the whole Earth), and the map type is specified as road map via the constant google.maps.MapTypeId.ROADMAP.


Note

image

Because the map object’s constructor contains a reference to the content of the HTML page, it can only be called once the website is loaded; that is, at window.onload.


7.1.2.2 OpenStreetMap/OpenLayers

OpenStreetMap was introduced in 2004 with the ambitious aim of becoming a comprehensive and free platform for geodata worldwide. Following the successful method adopted by Wikipedia, it was supposed to be easy for users to record geographical elements in their surrounding area and save them online. Considering the difficulty of editing geodata, the current state of the project is impressive. Thousands of users have uploaded their GPS data to the platform openstreetmap.org or corrected and commented on data on the website. Also, existing geodata with a suitable license was integrated into the database (for example, the US TIGER data and the Landsat 7 satellite images).

Several tools were created in association with the project, with which you can download data from the OpenStreetMap servers and – provided you have permission – upload and save that data to the server. The open interface makes it easy for software developers to integrate their products into the system.

A significant factor in the success of OpenStreetMap is the simple option for web developers to integrate maps into their websites through the OpenLayers project. This JavaScript library is not limited to OpenStreetMap but can definitely show its strength through this interaction. With OpenLayers, you can also access maps by Google, Microsoft, Yahoo, and countless other geographic services (based on the standards WMS and WFS).

A mini example of a road map in Central Europe with OpenLayers and OpenStreetMap is provided in Listing 7.2:

Listing 7.2 Road map of Central Europe with OpenStreetMap and OpenLayers


<!DOCTYPE html>
 <html>
 <head>
 <title>Geolocation - OpenLayers / OpenStreetMap</title>
 <script src=
 "http://www.openlayers.org/api/OpenLayers.js"></script>
 <script src=
 "http://www.openstreetmap.org/openlayers/OpenStreetMap.js">
 </script>
 <script>
  window.onload = function() {
    var map = new OpenLayers.Map("map");
    map.addLayer(new
      OpenLayers.Layer.OSM.Osmarender("Osmarender"));
    var lonLat = new OpenLayers.LonLat(11, 47).transform(
        new OpenLayers.Projection("EPSG:4326"),
        map.getProjectionObject()
    );
    map.setCenter (lonLat,7);
  }
 </script>
 <body>
  <div id="map" style="top: 0; left: 0; bottom: 0;
    right: 0; position: fixed;"></div>
 </body>
</html>


For this example, we need to load both the JavaScript library of openlayers.org and the library of openstreetmap.org. Similar to Google Maps, an HTML div element is assigned to the OpenLayers.Map object for representation, and a layer of the type Osmarender is added—the standard map view of OpenStreetMap (OSM). Here, a special feature of OpenStreetMap comes into play: As mentioned in section 7.1.1, About Geographical Data, three-dimensional information must be projected to be displayed in 2D on the screen. Although Google Maps does not harass the user with these details and you simply specify the x and y coordinates in decimal degrees, OpenLayers asks you to first project data in decimal degrees into the relevant coordinate system. Internally, OpenLayers (just like Google Maps, Yahoo! Maps, and Microsoft Bing Maps) creates the map representation with a projection, the so-called Spherical Mercator (EPSG code 3785). In Spherical Mercator, coordinates are managed in meters instead of decimal degrees, which is why the degree values used here must be converted to the coordinate system used in the map (determined with the function map.getProjectionObject()) with the call transform() and specify the EPSG code of the desired projection (EPSG:4326).


Warning

image

If you use DOCTYPE at the beginning of the document, as is correct with HTML5, the HTML element in which the map is displayed must contain a position of fixed or absolute. Otherwise, the OpenLayers library displays nothing. Interestingly, this limitation does not apply if no DOCTYPE is included. More information on this topic can be found in a posting on the mailing list at http://openlayers.org/pipermail/users/2009-July/012860.html.


7.2 A First Experiment: Geolocation in the Browser

To test your browser’s geolocation function, you just need the JavaScript code in Listing 7.3:

Listing 7.3 Function for outputting position with “navigator.geolocation”


function $(id) { return document.getElementById(id); }
window.onload = function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
        function(pos) {
          $("lat").innerHTML = pos.coords.latitude;
          $("lon").innerHTML = pos.coords.longitude;
          $("alt").innerHTML = pos.coords.altitude;
        },
        function() {},
        {enableHighAccuracy:true, maximumAge:600000}
    );
  } else {
    $("status").innerHTML =
      'No Geolocation support for your Browser';
  }
 }


The first line of the listing defines an auxiliary function $, allowing for an abbreviated notation of the function document.getElementById() (similar to an alias). This trick was taken from the familiar jQuery library and is very convenient for our example, because the elements that need to be filled are marked with an ID attribute on the website. As in the previous examples (see Listings 7.1 and 7.2), window.onload ensures that the content of the website is fully loaded before references to HTML elements are set. The first if query checks if the browser supports the Geolocation API. If that is not the case, an appropriate message is written into the element with the ID status. Otherwise, the actual function for determining position is activated: navigator.geolocation.getCurrentPosition().

According to the specification, the browser has to ask when calling this function if you want it to locate your current position and share it on the website. Figure 7.1 shows the relevant dialog box in Mozilla Firefox.

Figure 7.1 Mozilla Firefox asks for permission to share your location

image

Three arguments are passed to the function call:

• A function to be executed after the position has successfully been determined (success callback)

• A function that can react to errors if the position could not be determined (error callback)

• Value pairs influencing how the position is determined

According to the specification, the two latter arguments are optional; the success callback always has to be specified. So as not to impede the JavaScript sequence, getCurrentPosition() has to be executed asynchronously in the background, and the relevant callback function can only be called once the position is known or an error has occurred.

In this very short example, both callback functions are implemented as anonymous functions; errors are not considered. The value pair enableHighAccuracy: true tells the browser to calculate the position as accurately as possible. On an Android cell phone, this setting causes activation of the internal GPS sensor (more on this in section 7.3, Technical Background of Determining Position). Finally, maximumAge specifies the time in milliseconds during which an already determined position can be reused. After that time, the position has to be redetermined—in our case, every ten minutes.

After successfully determining the position, the variable pos of the success callback in the so-called Position interface contains coordinate data (pos.coords) plus a timestamp in milliseconds since 1970 (pos.timestamp). Figure 7.2 shows the available attributes and their respective values, if present.

Figure 7.2 Geographic position output in Mozilla Firefox

image

In addition to latitude, longitude, and altitude, pos.coords also includes information about the accuracy of the position (accuracy, altitudeAccuracy) plus possible speed and direction (heading). Whereas Google Chrome is limited to the attributes required in the specification, Firefox (here, version 3.6) outputs quite a lot of additional information—even address details (see Listing 7.4), showing an extract of the result of JSON.stringify(pos):

Listing 7.4 Extract from the result of JSON.stringify(pos) for Firefox 3.6


{"coords":
..// ...
  "address":
    {"streetNumber":"6","street":"Postgasse",
     "premises":null,"city":"Murnau am Staffelsee",
     "county":"Garmisch-Partenkirchen","region":"Bavaria",
     "country":"Germany","countryCode":"DE",
     "postalCode":"82418","contractID":"",
     "classDescription":"wifi geo position address object",
     // ...
    },
  // ...
}


The browser offers a remarkable amount of information! Where it all comes from will be explained in the following section.

7.3 Technical Background of Determining Position

If you access the website http://www.google.com from abroad, you may be surprised to find that you are automatically redirected to the relevant Google domain of the country you are in. This works even if your browser is not geolocation capable: Google uses a simple trick and locates your whereabouts via the IP address.

Browsers supporting the Geolocation API can achieve a significantly greater accuracy by making use of other technical options. The following four methods are currently in use:

1. In PCs with wired Internet connections, the position is located via the IP address. This way of determining position is rather inaccurate, as you would expect.

2. The position can be determined much more precisely if there is a wireless LAN connection. Google has collected data worldwide from public and private WLANs.

3. If the hardware has a mobile communications chip (for example, in a smartphone), it tries to calculate the position within the mobile communications network.

4. If the hardware also has a GPS sensor, the position can be determined even more accurately. GPS is a satellite-based positioning system and can achieve accuracy to the meter range even with cheap sensors, provided the conditions are favorable (outside of buildings, unobstructed horizon, etc.).

Only the GPS sensor works offline; methods 1–3 require Internet access and are implemented through a server location service. These services are available from Google (Google Location Service, used in Firefox, Chrome, and Opera) and another American company, Skyhook Wireless (used in Safari and early versions of Opera).

But how do the service providers get the location information of wireless and mobile networks? In parallel with the photos taken by Google for the service Street View, the Google Street View vehicles also save information on public and private WLANs. The revelation, in spring 2010, that these vehicles collected not only the MAC address and SSID of the WLAN, but also user data, shed a bad light on Google, resulting in several public apologies.

But that is not all: If the browser has access to the information on a mobile network or wireless LAN router, this data is sent with every call of the service. For Google, this concerns mainly mobile communication devices with the Android operating system; Skyhook profits from the iPhone users. The combination of the described methods leads to a very large data set of geodata available to these two service providers and is continuously updated through crowdsourcing (even if the users as data providers do not know anything about it).


Tip

image

Firefox has a very useful extension in the add-on Geolocater, which is particularly helpful for developing applications. It allows for entering locations that Firefox returns when the Geolocation API is called. You can select the location via a pull-down menu without having to resort to Google’s online service. You can download this useful add-on at https://addons.mozilla.org/en-US/firefox/addon/14046.


7.4 Display of Current Position on OpenStreetMap

In the following example, the current location is represented on a map of OpenStreetMap and indicated with a marker. You can see different layers and the OpenStreetMap navigation bar. Figure 7.3 shows the OpenStreetMap’s Mapnik layer with the position marker in the center of the browser.

Figure 7.3 Current location using OpenLayers and OpenStreetMap

image

© OpenStreetmap contributors, CC-BY-SA

Just as in section 7.1.2, Online Map Services, the data of the OpenStreetMap project is represented using the OpenLayers library. After the two required JavaScript files are loaded, the map is initialized in this example and the desired control elements are added:

// Initialize map and add navigation
var map = new OpenLayers.Map ("map");
map.addControl(new OpenLayers.Control.Navigation());
map.addControl(new OpenLayers.Control.PanZoomBar());

In addition to the navigation element with the four arrows, we attach the zoom bar to the map variable (map). We then create the selection element for the various layers (Control.LayerSwitcher) and add several layers to the map. The function call of map.addLayers() receives an array of newly created map objects:

// Layer selection with four map types
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.addLayers([
  new OpenLayers.Layer.OSM.Mapnik("Mapnik"),
  new OpenLayers.Layer.OSM.Osmarender("Osmarender"),
  new OpenLayers.Layer.OSM.CycleMap("CycleMap")
]);

To finish, the map gets a layer for the marker:

var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);

The success callback after successfully determining the position looks like this:

          function(pos) {
            var ll = new OpenLayers.LonLat(
              pos.coords.longitude,
              pos.coords.latitude).transform(
                new OpenLayers.Projection("EPSG:4326"),
                map.getProjectionObject()
              );
            map.setCenter (ll,zoom);
            markers.addMarker(
              new OpenLayers.Marker(
              ll,new OpenLayers.Icon(
'http://www.openstreetmap.org/openlayers/img/marker.png')
              )
            );
          },

As you already know from section 7.1.2, Online Map Services, the coordinates from the geographical coordinate system (lat/lon) must be converted to the Spherical Mercator system. Finally, the marker ll is placed on the determined location; the relevant icon for the marker is loaded directly off the OpenStreetMap The Geolocation specification includes another call, particularly suitable for moving objects: navigator.geolocation.watchPosition(). The next example demonstrates how a change in location can be represented graphically using the Google Maps API.

7.5 Location Tracking with Google Maps

Our quick example only makes sense if used on mobile devices. Of course, you can “get things moving” artificially for demo purposes, but you will most likely only get a real sense of achievement once you manage to determine your location accurately via GPS and using a browser while on the move. A crucial component of the following experiment was an Android smartphone showing the HTML page during a trip down the highway.

As you can see in Figure 7.4, the last five locations determined on Google Maps are marked on the map. As soon as the user leaves the map area represented on the screen, the map is centered around the next point.

Figure 7.4 Google Maps API on an Android cell phone

image

Calling the Geolocation API is once again done in window.onload and looks like this:

var watchID = navigator.geolocation.watchPosition(
  moveMe, posError, {enableHighAccuracy: true}
);

The real work takes place in the function moveMe():

function moveMe(position) {
  latlng = new google.maps.LatLng(
    position.coords.latitude,
    position.coords.longitude);
  bounds = map.getBounds();
  map.setZoom(16);
  if (!bounds.contains(latlng)) {
    map.setCenter(latlng);
  }
  if (marker.length >= maxMarkers) {
    m = marker.shift();
    if (m) {
      m.setMap();
    }
  }
  marker.push(new google.maps.Marker({
    position: latlng, map: map,
    title: position.coords.accuracy+"m lat: "
      +position.coords.latitude+" lon: "+
      position.coords.longitude
  }));
 }

The variable latlng is created as a LatLng object from the Google Maps API, and the current coordinates are passed to this object. If the current location is outside of the represented area (!bounds.contains(latlng)), the map is re-centered over the current point. Both the array marker and the variable maxMarkers at the beginning of the script are defined as global and assigned the value 5. If the array marker contains more than five elements, the first element is removed from the array with the shift function and then deleted from the map by calling setMap() without any further parameters. Finally, a new object of the type marker is added to the array in the current location.

7.6 Example: Geonotes

The idea for this example originated during a trip abroad with a new smartphone: The program is a digital travel diary that automatically adds geographical coordinates to each entry and can display all entries on a map. The high data-roaming charges in Europe soon made it necessary to integrate another technology related to HTML5—Web Storage—to keep costs down. Via the Web Storage API, the entries are stored locally in persistent memory, allowing the application to function even without an existing data connection. For a detailed explanation of the Web Storage API, see Chapter 8, Web Storage and Offline Web Applications.

7.6.1 Operation

The application has a very simple structure (see Figure 7.5): In the text box (top left) you can enter your diary notes. The new HTML5 placeholder attribute lets the browser show an invitation to enter a new message. If you have already entered notes, the area on the right displays a map section of Google Maps. Underneath is the list of entries, including not just the message text, but also location, time of entry, and distance to current location. You also have the option of deleting messages or displaying the location enlarged on Google Maps. As you can see in Figure 7.5, the enlarged representation indicates the location with a marker typical for Google. The circle around the location marker indicates the accuracy of the determined location.

Figure 7.5 Notes with additional geographic information

image

Because you tend not to constantly change location while developing an application, the Firefox add-on Geolocater, introduced in section 7.3, Technical Background of Determining Position, comes in handy. You have the option of saving several locations in the add-on, allowing you to test the application while at home. Ideally though, the application would be used on a smartphone with GPS support. Both Android-based cell phones and the iPhone fulfill the necessary requirements.

To be able to test the application right away, you can use the demo data. These entries are partly made up and partly actual entries recorded by the author while developing the application.

7.6.2 Important Code Fragments

The HTML code for the application offers several div container elements, which will later house the messages (id='items') and the map (id='map'). As mentioned previously, the textarea element contains the new placeholder attribute, which can make applications much more user friendly. The relevant onclick event listener is directly assigned to the three button elements:

<body>
  <h1>Geonotes</h1>
  <div class='text_input'>
    <textarea style='float:left;margin-right:30px;'
      placeholder='Your message here ...'
      cols="50" rows="15" id="note"></textarea>
    <div class='map' id='map'></div>
    <div style='clear:both;' id='status'></div>
    <button style='float:left;color:green;' id='save'
      onclick='saveItem()'>Save</button>
    <button onclick='drawAllItems()'>Draw all items on
      map</button>
    <button onclick='importDemoData()'>Import Demo Data
    </button>
  </div>
  <div class='items' id='items'></div>

The JavaScript code is much more interesting than the few lines of HTML code. It defines an auxiliary function and three global variants:

function $(id) { return document.getElementById(id); }
 var map;
 var my_pos;
 var diaryItem = { id: 0, pos: 0, ts: 0, msg: '' }

You have already encountered the function $ in section 7.2, A First Experiment: Geolocation in the Browser. It saves you a lot of typing effort here, too, and makes the code easier to read. The variable map serves as a reference to the HTML area, which will accommodate the Google Maps representation. my_pos is required for calculating the distance and contains the current location from which the script is called. diaryItem represents the structure of the individual entries. Each diary entry is assigned an ID (id), information on the current position (pos), a timestamp (ts), and the message entered into the text field (msg).

As soon as the page is fully loaded, the current location is determined and existing entries are displayed:

window.onload = function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      function(pos) {
        my_pos = pos;
        showItems();
      },
      posError,
      { enableHighAccuracy: true, maximumAge: 60000 }
    );
  }
  showItems();
  if (localStorage.length > 0) {
    drawAllItems();
  }
}

The option enableHighAccuracy is activated to call getCurrentPosition(). The maximum time for reusing an already determined position is one minute. If the position is successfully determined, the previously defined global variable my_pos is assigned the values of the just determined position and then the function showItems() is called. An error in determining the position leads to calling the function posError(), a function that outputs the corresponding error message in a dialog window. If the number of elements in the localStorage is greater than 0, the function drawAllItems() is executed as well, displaying existing entries on Google Maps.

The showItems function assembles a string of all entries and assigns it to the HTML element with the ID items:

function showItems() {
  var s = '<h2>'+localStorage.length+' Items for '
    +location.hostname+'</h2>';
  s+= '<ul>';
  var i_array = getAllItems();
  for (k in i_array) {
    var item = i_array[k];
    var iDate = new Date(item.ts);
    s+= '<li>';
    s+= '<p class="msg">'+item.msg+'</p>';
    s+= '<div class="footer">';
    s+= '<p class="i_date">'+iDate.toLocaleString();
      +'</p>';
 ...
  $('items').innerHTML = s+'</ul>';

The variable i_array is filled with the result of the function getAllItems(), which reads the localStorage, returns the contents as objects in an array, and sorts the objects by date:

function getAllItems() {
  var i_array = [];
  for (var i=0;i<localStorage.length;i++) {
    try {
      var item = JSON.parse(
        localStorage.getItem(localStorage.key(i))
      );
      i_array.push(item);
    } catch (err) {
      continue;   // skip this entry, no valid JSON data
    }
  }
  i_array.sort(function(a, b) {
    return b.ts - a.ts
  });
  return i_array;
 }

The call localStorage.getItem() gets an element from the persistent memory, converting it to a JavaScript object via the function JSON.parse. The requirement is that the object be converted to a string with JSON.stringify during saving (see the following code listing). To avoid the script being aborted due to any items in local storage that are not JSON encoded, the instruction is enclosed in a try/catch block. The objects are added to the end of the array i_array with i_array.push() and sorted by date in the next step. To tell the JavaScript function sort which criteria it should sort by, it is expanded with an anonymous function. The variable ts allows temporal sorting of the objects. It contains the numbers of milliseconds since 1.1.1970, a value created via the JavaScript function new Date().getTime(). If the anonymous function returns a negative value, a is arranged after b; for a positive value, a comes before b.

We still need to answer the question about how new entries are created and saved. The function saveItem() takes care of this, initializing a local variable d to which we assign the structure diaryItem:

function saveItem() {
  var d = diaryItem;
  d.msg = $('note').value;
  if (d.msg == '') {
    alert("Empty message");
    return;
  }
  d.ts = new Date().getTime();
  d.id = "geonotes_"+d.ts;
  if (navigator.geolocation) {
    $('status').innerHTML = '<span style="color:red">'
        +'getting current position / item unsaved</span>';
    navigator.geolocation.getCurrentPosition(
      function(pos) {
        d.pos = pos.coords;
        localStorage.setItem(d.id, JSON.stringify(d));
        $('status').innerHTML =
          '<span style="color:green">item saved. Position'
          +' is: '+pos.coords.latitude
          +','+pos.coords.longitude+'</span>';
        showItems();
      },
      posError,
      { enableHighAccuracy: true, maximumAge: 60000 }
    );
  } else {
    // alert("Browser does not support Geolocation");
    localStorage.setItem(d.id, JSON.stringify(d));
    $('status').innerHTML =
      "Browser does not support Geolocation/item saved.";
  }
  showItems();
 }

If the text field is empty (d.msg = ''), a corresponding dialog appears and the function is terminated with return. Otherwise, the timestamp is set to the current millisecond, and the entry’s ID is assembled from the string geonotes_ and the timestamp. If several applications should access the localStorage from one server, the string prefix can help to distinguish the data. After the position has been successfully determined, the variable pos within the diaryItem object is filled with coordinates and the appropriate meta information, and then saved as a JSON string in the localStorage via JSON.stringify().

If the browser does not support the Geolocation API, the application saves the text anyway and points out that there is no support. The final call of showItems() ensures that the list of messages is updated.

7.7 Browser Support

As mentioned previously, the functions for determining location offer many new possibilities, especially for use on mobile devices. The most important mobile platforms at the time of this writing are products by Apple (iPhone, iPad, iPod) and Android cell phones. Both Google’s browser (standard on the Android platform) and Safari (for Apple devices) support the Geolocation API.

Desktop browsers also offer a good level of support. Safari and Google Chrome include the required functions from version 5 and later; Firefox has been Geolocation-capable since version 3.5. Opera integrates the function in its browser in version 10.60 and later. Only Microsoft still fails to offer support for any kind of geolocation in the browser, and unfortunately, this even applies to the mobile platform Windows Phone 7.

Summary

In this chapter you encounter the new geolocation functions, which open amazing new possibilities, especially for mobile devices. With the rapid spread of smartphones, location-based services are becoming available to more and more people. They make it easy for users on the move to gather information, be it finding the nearest cash machine or the best public transport connection. At the moment, these tasks are still carried out by special apps that have to be developed and constantly updated separately for each mobile operating system. By implementing the Geolocation API, such functions can in the future be handled by the browser.

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

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