Practice: Create geolocation components

Return to article

Solution

Here is the solution to the exercise:

  • Your initialization function should look similar to the one shown in Listing 2. The navigator.geolocation.getCurrentPositon() method returns the host device's current position to the geolocationSuccess callback, with a position object as the parameter.
    Listing 2. Geolocation initialization function
    	    function initGeoApp()
    	    {
    	            if( navigator.geolocation )
    	            {
    	 
    	              navigator.geolocation.getCurrentPosition( success, failure);
    	        }
    	        else
    	        {
    	              alert("Your browser does not support geolocation services.");
    	        }
    	    }
  • The watchPosition() method polls the user location on a regular basis. It watches to see whether the user's location has changed. watchPosition asynchronously starts a watch process involving the acquisition of a new position object and creation of a watchID. The watchPosition() method is called as shown in Listing 3.
    Listing 3. The geolocation.watchPosition method
    long navigator.geolocation.watchPosition(
              success, failure, options);
  • Use the clearWatch() method to terminate a watchPosition(). This method looks for the watchID argument that was previously started and stops it. Your clearWatch() method definition should be similar to that shown in Listing 4.
    Listing 4. The geolocation.clearWatch method
    void navigator.geolocation.clearWatch(watchID)
  • To retrieve the values based on the IDs supplied in Listing 1 using document.getElementById, create statements similar to those in Listing 5.
    Listing 5. Get position values
    document.getElementById("accuracyValue").innerHTML = position.coords.accuracy;
    document.getElementById("altitudeValue").innerHTML = position.coords.altitude;
    document.getElementById("altitudeAccuracyValue").innerHTML 
                 = position.coords.altitudeAccuracy;
    document.getElementById("headingValue").innerHTML = position.coords.heading;
    document.getElementById("latitudeValue").innerHTML = position.coords.latitude;
    document.getElementById("longitudeValue").innerHTML = position.coords.longitude;
    document.getElementById("speedValue").innerHTML = position.coords.speed;

Return to article