geo2.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. function isGeoAvailable() {
  2. "use strict";
  3. return navigator.geolocation;
  4. }
  5. function setMessage(message) {
  6. "use strict";
  7. var geo = document.getElementById("geo");
  8. if (geo) {
  9. geo.innerHTML = message;
  10. }
  11. else {
  12. console.log("setMessage()", message);
  13. }
  14. }
  15. function getPositionMessage(position) {
  16. "use strict";
  17. var coords = position.coords;
  18. var date = new Date(position.timestamp);
  19. var message = "<p>Position: </p>\n" +
  20. "<ul>\n" +
  21. " <li>Timestamp: " + position.timestamp + " = " + date.toLocaleString() + "</li>\n" +
  22. " <li>Accuracy: " + coords.accuracy + " meters</li>\n" +
  23. " <li>Latitude: " + coords.latitude + "</li>" +
  24. " <li>Longitude: " + coords.longitude + "</li>" +
  25. " <li>Altitude: " + (coords.altitude ? coords.altitude : "unknown") + "</li>" +
  26. " <li>Altitude Accuracy: " + (coords.altitudeAccuracy ? coords.altitudeAccuracy : 0) + "</li>" +
  27. " <li>Heading: " + (coords.heading ? coords.heading : "unknown") + "</li>\n" +
  28. " <li>Speed: " + (coords.speed ? coords.speed : "unknown") + "</li>\n"
  29. " </ul>\n";
  30. return message;
  31. }
  32. function showPositionMessage(position) {
  33. "use strict";
  34. setMessage("showPositionMessage()", getPositionMessage(position));
  35. }
  36. function showPositionError(error) {
  37. "use strict";
  38. var reason;
  39. switch (error.code) {
  40. case error.POSITION_UNAVAILABLE:
  41. reason = "Position unavailable";
  42. break;
  43. case error.PERMISSION_DENIED:
  44. reason = "Permission denied";
  45. break;
  46. case error.TIMEOUT:
  47. reason = "Timeout"
  48. break;
  49. default:
  50. reason = "Unknown position error (" + error.code + ")";
  51. break;
  52. }
  53. setMessage(reason + ": " + error.message);
  54. }
  55. if (isGeoAvailable()) {
  56. navigator.geolocation.getCurrentPosition(showPositionMessage, showPositionError);
  57. }
  58. else {
  59. setMessage('Geolocation API is not available.');
  60. }