In our article
HTML 5 Geolocation: A Practical Example
we created a scenario for a Store Locator to illustrate all of the most commonly used HTML 5 Geolocation properties and methods. We are now going to step beyond the common to the uncommon and illustrate some of the less used but arguably more interesting properties and methods like
coords.altitude
,
coords.heading
and
watchPosition()
.
Note: The common properties and methods like coords.latitude and coords.longitude are used in the example below but will not be covered. Other topics not covered include calculating distance between two points, showing a location with Google Maps, and error handling. If you are not familiar with these topics please refer to our article HTML 5 Geolocation: A Practical Example.
Setting up the Scenario
We are building a new website for mountain climbers. As part of our new application we are offering a web page that will track a climber’s movement giving them up-to-date information such as their current location, distance to the mountain peak, altitude, speed and heading.
The Markup and Script
Mountain Climber Tracker
Select your mountain destination:
Mount Elbert, Colorado
Mount Mitchell, North Carolina
Mount Rainier, Washington
We tried but we can’t calculate your location.
Tracking your progress:
Map image.
// Elements that we will need to manipulate
var InputElements = document.getElementById(“MountainClimberTrackerInputElements”);
var locationError = document.getElementById(“Error”);
var resultsTitle = document.getElementById(“TrackingTitle”);
var resultsContent = document.getElementById(“TrackingResults”);
var googleMap = document.getElementById(“GoogleMap”);
// Create a two dimensional array for keeping our store data
var mountainData = new Array(3)
createTwoDimensionalArray(3);
// Variable to track the selected mountain index in our array
var mountainDataIndex = 0;
// Variable to track position watch ID
var watchPositionId = 0;
// Mountain information
mountainData[0][0] = “Mount Elbert, Colorado”;
mountainData[1][0] = “Mount Mitchell, North Carolina”;
mountainData[2][0] = “Mount Rainier, Washington”;
// Mountain latitude
mountainData[0][1] = “39.1178512”;
mountainData[1][1] = “35.7649612”;
mountainData[2][1] = “46.8529129”;
// Mountain longitude
mountainData[0][2] = “-106.4451599”;
mountainData[1][2] = “-82.26511”;
mountainData[2][2] = “-121.7604446”;
// This function creates our two dimensional array
function createTwoDimensionalArray(arraySize) {
for (i = 0; i < mountainData.length; ++i)
mountainData[i] = new Array(arraySize);
}
// Function to determine if browser supports geolocation
function checkGeolocationSupport() {
if (navigator.geolocation) {
// Show mountain selection options – radio buttons –
// otherwise send to function that shows the specific reason why location cannot be determined
InputElements.style.display = ‘block’;
locationError.style.display = ‘none’;
resultsTitle.style.display = ‘none’;
resultsContent.style.display = ‘none’;
googleMap.style.display = ‘none’;
}
else {
// Browser does not support geolocation
InputElements.style.display = ‘none’;
locationError.style.display = ‘block’;
locationError.innerHTML = ‘We cannot show your location because your browser does not support HTML 5 geolocation.’;
resultsTitle.style.display = ‘none’;
resultsContent.style.display = ‘none’;
googleMap.style.display = ‘none’;
}
}
function startTracking(mountainIndex) {
// Set index tracking variable to selected mountain data array index
mountainDataIndex = mountainIndex;
// Clear position watch
navigator.geolocation.clearWatch(watchPositionId);
// Start watching location
watchPositionId = navigator.geolocation.watchPosition(showClimberLocation, showError, { enableHighAccuracy: false, maximumAge: 60000, timeout: 30000 });
}
function showClimberLocation(position) {
// Hide/show appropriate elements
InputElements.style.display = ‘block’;
locationError.style.display = ‘none’;
resultsTitle.style.display = ‘block’;
resultsContent.style.display = ‘block’;
googleMap.style.display = ‘block’;
// Determine current distance to mountain
var currentDistance;
currentDistance = calculateDistance(position.coords.latitude, position.coords.longitude, mountainData[mountainDataIndex][1], mountainData[mountainDataIndex][2]);
var timestampDate = new Date(position.timestamp);
// Build results
var geoloactionResults = ”;
geoloactionResults = ‘’ + mountainData[mountainDataIndex][0] + ‘
Distance to peak (miles): ‘ + Math.round(currentDistance * 10) / 10 + ‘
’;
geoloactionResults = geoloactionResults + ‘ Position (latitude, longitude): ‘ + position.coords.latitude + ‘, ‘ + position.coords.longitude + ‘
’;
geoloactionResults = geoloactionResults + ‘ (position accurate to within ‘ + Math.round(convertMetersToFeet(position.coords.accuracy)) + ‘ feet)
’;
if ((position.coords.altitude == null) || ((position.coords.altitude == 0) && (position.coords.altitudeAccuracy == 0))) {
// Altitude cannot be determined — generate appropriate message
geoloactionResults = geoloactionResults + ‘ Altitude could not be determined.
’;
}
else {
// Calculate and display results normally
geoloactionResults = geoloactionResults + ‘ Current Altitude: ‘ + position.coords.altitude + ‘
’;
geoloactionResults = geoloactionResults + ‘ (altitude accurate to within ‘ + Math.round(convertMetersToFeet(position.coords.altitudeAccuracy)) + ‘ feet)
’;
}
if ((position.coords.heading == null) || (isNaN(position.coords.heading))) {
// Heading cannot be determined — generate appropriate message
geoloactionResults = geoloactionResults + ‘ Heading could not be determined.
’;
}
else {
// Calculate and display results normally
geoloactionResults = geoloactionResults + ‘ Heading: ‘ + position.coords.heading + ‘ (360 degree heading with North being 0)
’;
}
if ((position.coords.speed == null) || (isNaN(position.coords.speed))) {
// Heading cannot be determined — generate appropriate message
geoloactionResults = geoloactionResults + ‘ Speed could not be determined.
’;
}
else {
// Calculate and display results normally
geoloactionResults = geoloactionResults + ‘ Speed: ‘ + position.coords.speed + convertMetersPerSecondToMilesPerHour(position.coords.speed) + ‘ (converted from meters per second to miles per hour)
’;
}
geoloactionResults = geoloactionResults + ‘ Last Updated: ‘ + timestampDate.toLocaleString();
// Show results
resultsContent.innerHTML = geoloactionResults;
// Show map
var googleLatitudeLongitude = position.coords.latitude + “,” + position.coords.longitude;
var mapImageUrl = “http://maps.googleapis.com/maps/api/staticmap?center=” + googleLatitudeLongitude + “&zoom=12&size=300×300&sensor=false”;
googleMap.innerHTML = “