97 lines
2.3 KiB
JavaScript
97 lines
2.3 KiB
JavaScript
/**
|
|
* A wrapper around HTML5 Geolocation with helper methods.
|
|
*
|
|
* @constructor
|
|
*/
|
|
function Geo() {
|
|
"use strict";
|
|
|
|
/**
|
|
* @type {Geolocation}
|
|
*/
|
|
var geo = navigator.geolocation;
|
|
|
|
this.getGeo = function () {
|
|
return geo;
|
|
};
|
|
|
|
/**
|
|
*
|
|
* @param {MessageElement} area
|
|
*/
|
|
this.showLocation = function (area) {
|
|
var that = this;
|
|
geo.getCurrentPosition(
|
|
function (position) {
|
|
area.set(that.getPositionMessage(position));
|
|
},
|
|
function (error) {
|
|
area.set(that.getPositionError(error));
|
|
}
|
|
);
|
|
};
|
|
|
|
/**
|
|
* Build a string representation of a Geolocation PositionError.
|
|
*
|
|
* @param {PositionError} error
|
|
*
|
|
* @returns {*}
|
|
*/
|
|
this.getPositionError = function(error) {
|
|
"use strict";
|
|
var reason;
|
|
switch (error.code) {
|
|
case error.POSITION_UNAVAILABLE:
|
|
reason = "Position unavailable";
|
|
break;
|
|
case error.PERMISSION_DENIED:
|
|
reason = "Permission denied";
|
|
break;
|
|
case error.TIMEOUT:
|
|
reason = "Timeout"
|
|
break;
|
|
default:
|
|
reason = "Unknown position error (" + error.code + ")";
|
|
break;
|
|
}
|
|
|
|
var ret = reason + ": " + error.message;
|
|
return ret;
|
|
};
|
|
|
|
/**
|
|
* Build a HTML-formatted representation of a position information.
|
|
*
|
|
* @param {Position} position
|
|
* @returns {string}
|
|
*/
|
|
this.getPositionMessage = function (position) {
|
|
/**
|
|
* @type {Coordinates}
|
|
*/
|
|
var coords = position.coords;
|
|
|
|
var date = new Date(position.timestamp);
|
|
|
|
var message = "<p>Position: </p>\n" +
|
|
"<ul>\n" +
|
|
" <li>Timestamp: " + position.timestamp + " = " + date.toLocaleString() + "</li>\n" +
|
|
" <li>Accuracy: " + coords.accuracy + " meters</li>\n" +
|
|
" <li>Latitude: " + coords.latitude + "</li>" +
|
|
" <li>Longitude: " + coords.longitude + "</li>" +
|
|
" <li>Altitude: " + (coords.altitude ? coords.altitude : "unknown") + "</li>" +
|
|
" <li>Altitude Accuracy: " + (coords.altitudeAccuracy ? coords.altitudeAccuracy : 0) + "</li>" +
|
|
" <li>Heading: " + (coords.heading ? coords.heading : "unknown") + "</li>\n" +
|
|
" <li>Speed: " + (coords.speed ? coords.speed : "unknown") + "</li>\n" +
|
|
" </ul>\n";
|
|
|
|
return message;
|
|
};
|
|
|
|
this.init = function () {
|
|
geo = navigator.geolocation || false;
|
|
};
|
|
|
|
this.init();
|
|
}
|