Geo.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * A wrapper around HTML5 Geolocation with helper methods.
  3. *
  4. * @constructor
  5. */
  6. function Geo() {
  7. "use strict";
  8. /**
  9. * @type {Geolocation}
  10. */
  11. var geo = navigator.geolocation;
  12. this.getGeo = function () {
  13. return geo;
  14. };
  15. /**
  16. *
  17. * @param {MessageElement} area
  18. */
  19. this.showLocation = function (area) {
  20. var that = this;
  21. geo.getCurrentPosition(
  22. function (position) {
  23. area.set(that.getPositionMessage(position));
  24. },
  25. function (error) {
  26. area.set(that.getPositionError(error));
  27. }
  28. );
  29. };
  30. /**
  31. * Build a string representation of a Geolocation PositionError.
  32. *
  33. * @param {PositionError} error
  34. *
  35. * @returns {*}
  36. */
  37. this.getPositionError = function(error) {
  38. "use strict";
  39. var reason;
  40. switch (error.code) {
  41. case error.POSITION_UNAVAILABLE:
  42. reason = "Position unavailable";
  43. break;
  44. case error.PERMISSION_DENIED:
  45. reason = "Permission denied";
  46. break;
  47. case error.TIMEOUT:
  48. reason = "Timeout"
  49. break;
  50. default:
  51. reason = "Unknown position error (" + error.code + ")";
  52. break;
  53. }
  54. var ret = reason + ": " + error.message;
  55. return ret;
  56. };
  57. /**
  58. * Build a HTML-formatted representation of a position information.
  59. *
  60. * @param {Position} position
  61. * @returns {string}
  62. */
  63. this.getPositionMessage = function (position) {
  64. /**
  65. * @type {Coordinates}
  66. */
  67. var coords = position.coords;
  68. var date = new Date(position.timestamp);
  69. var message = "<p>Position: </p>\n" +
  70. "<ul>\n" +
  71. " <li>Timestamp: " + position.timestamp + " = " + date.toLocaleString() + "</li>\n" +
  72. " <li>Accuracy: " + coords.accuracy + " meters</li>\n" +
  73. " <li>Latitude: " + coords.latitude + "</li>" +
  74. " <li>Longitude: " + coords.longitude + "</li>" +
  75. " <li>Altitude: " + (coords.altitude ? coords.altitude : "unknown") + "</li>" +
  76. " <li>Altitude Accuracy: " + (coords.altitudeAccuracy ? coords.altitudeAccuracy : 0) + "</li>" +
  77. " <li>Heading: " + (coords.heading ? coords.heading : "unknown") + "</li>\n" +
  78. " <li>Speed: " + (coords.speed ? coords.speed : "unknown") + "</li>\n" +
  79. " </ul>\n";
  80. return message;
  81. };
  82. this.init = function () {
  83. geo = navigator.geolocation || false;
  84. };
  85. this.init();
  86. }