geo2.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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("message:", 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(getPositionMessage(position));
  35. }
  36. function showPositionError(error) {
  37. "use strict";
  38. setMessage(error);
  39. }
  40. if (isGeoAvailable()) {
  41. navigator.geolocation.getCurrentPosition(showPositionMessage, showPositionError);
  42. }
  43. else {
  44. setMessage('Geolocation API is not available.');
  45. }