Getting geographical location input

One of the exciting new features in HTML5 is the geolocation API (http://www.w3.org/TR/geolocation-API/). It allows the developer to ask for the user's location. This API allows the developer to get geographic coordinates, such as latitude and longitude.

Before this API developers had to rely on more crude methods, such as GeoIP databases. These methods produced results that had poor accuracy. Depending on the user's browser, device, and the availability of GPS on it, the geolocation API could give results with a few meters accuracy.

In this recipe, we're going to display the user's location on a map. To do this, we're going to use the Leaflet library. The use of this library to show maps is covered in the Displaying a map recipe, Chapter 2, Display of Graphical Data.

How to do it...

Let's get started.

  1. We're going to create a HTML page with a map placeholder, which will include the leaflet library (both CSS and JS files) and our code for getting and displaying the user's location, located in example.js as shown in the following code snippet:
    <!DOCTYPE HTML>
    <html>
      <head>
        <title>Geolocation example</title>
         <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4/leaflet.css" />
         <!--[if lte IE 8]>
           <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4/leaflet.ie.css" />
         <![endif]-->
      </head>
      <body>
        <div id="map" style="height:480px; width:640px;"></div>
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
          <script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script>
          <script type="text/javascript" src="example.js"></script>
      </body>
    </html>
  2. And we're going to add the following code in example.js:
    $(function() {
      var map = L.map('map').setView([51.505, -0.09], 13)
    
      L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',{
        attribution:'Copyright (C) OpenStreetMap.org',
        maxZoom:18
        }).addTo(map);
    
      if ("geolocation" in navigator) {
        var marker = L.marker([51.5, -0.09]).addTo(map);
        var watchId = navigator.geolocation.watchPosition(function(position) {
        var userLatLng = new L.LatLng(position.coords.latitude, position.coords.longitude);
        marker.setLatLng(userLatLng);
        map.panTo(userLatLng);
        });
      }
      else alert("Sorry, geolocation is not supported in your browser");
    });

How it works...

The geolocation API is available through the geolocation object that can be found in the navigator object. There are multiple methods available, as follows:

  • getCurrentPosition: This method calls its callback function parameter one time after a location is obtained
  • watchCurrentPosition: This method calls its first callback function parameter every time the location information is updated and returns a watcher ID
  • clearWatch: This method removes the watch callback by clearing it using our returned watcher ID

In our example, we use watchCurrentPosition, and provide it with a callback, which sets the marker's position. The user will first be asked to give the website a permission to access his or her location. After the permission is given and a location is found, our callback will be called with a position object.

The position object contains the properties timestamp and coords. The coords property is an object containing latitude and longitude information. The timestamp property is a UNIX UTC timestamp denoting the time of the location information update.

There's more...

This example will not work when opened directly as a file. To view the example, a local server must be started in the same directory. For more information on how to start a local server, see Appendix, Installing and using http-server.

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

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