Spherical.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for
  2. * full list of contributors). Published under the 2-clause BSD license.
  3. * See license.txt in the OpenLayers distribution or repository for the
  4. * full text of the license. */
  5. /**
  6. * @requires OpenLayers/SingleFile.js
  7. */
  8. /**
  9. * Namespace: Spherical
  10. * The OpenLayers.Spherical namespace includes utility functions for
  11. * calculations on the basis of a spherical earth (ignoring ellipsoidal
  12. * effects), which is accurate enough for most purposes.
  13. *
  14. * Relevant links:
  15. * * http://www.movable-type.co.uk/scripts/latlong.html
  16. * * http://code.google.com/apis/maps/documentation/javascript/reference.html#spherical
  17. */
  18. OpenLayers.Spherical = OpenLayers.Spherical || {};
  19. OpenLayers.Spherical.DEFAULT_RADIUS = 6378137;
  20. /**
  21. * APIFunction: computeDistanceBetween
  22. * Computes the distance between two LonLats.
  23. *
  24. * Parameters:
  25. * from - {<OpenLayers.LonLat>} or {Object} Starting point. A LonLat or
  26. * a JavaScript literal with lon lat properties.
  27. * to - {<OpenLayers.LonLat>} or {Object} Ending point. A LonLat or a
  28. * JavaScript literal with lon lat properties.
  29. * radius - {Float} The radius. Optional. Defaults to 6378137 meters.
  30. *
  31. * Returns:
  32. * {Float} The distance in meters.
  33. */
  34. OpenLayers.Spherical.computeDistanceBetween = function(from, to, radius) {
  35. var R = radius || OpenLayers.Spherical.DEFAULT_RADIUS;
  36. var sinHalfDeltaLon = Math.sin(Math.PI * (to.lon - from.lon) / 360);
  37. var sinHalfDeltaLat = Math.sin(Math.PI * (to.lat - from.lat) / 360);
  38. var a = sinHalfDeltaLat * sinHalfDeltaLat +
  39. sinHalfDeltaLon * sinHalfDeltaLon * Math.cos(Math.PI * from.lat / 180) * Math.cos(Math.PI * to.lat / 180);
  40. return 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  41. };
  42. /**
  43. * APIFunction: computeHeading
  44. * Computes the heading from one LonLat to another LonLat.
  45. *
  46. * Parameters:
  47. * from - {<OpenLayers.LonLat>} or {Object} Starting point. A LonLat or
  48. * a JavaScript literal with lon lat properties.
  49. * to - {<OpenLayers.LonLat>} or {Object} Ending point. A LonLat or a
  50. * JavaScript literal with lon lat properties.
  51. *
  52. * Returns:
  53. * {Float} The heading in degrees.
  54. */
  55. OpenLayers.Spherical.computeHeading = function(from, to) {
  56. var y = Math.sin(Math.PI * (from.lon - to.lon) / 180) * Math.cos(Math.PI * to.lat / 180);
  57. var x = Math.cos(Math.PI * from.lat / 180) * Math.sin(Math.PI * to.lat / 180) -
  58. Math.sin(Math.PI * from.lat / 180) * Math.cos(Math.PI * to.lat / 180) * Math.cos(Math.PI * (from.lon - to.lon) / 180);
  59. return 180 * Math.atan2(y, x) / Math.PI;
  60. };