PageRenderTime 1108ms CodeModel.GetById 45ms RepoModel.GetById 0ms app.codeStats 0ms

/src/geo/LatLng.js

https://bitbucket.org/Zedd45/leaflet
JavaScript | 60 lines | 44 code | 11 blank | 5 comment | 5 complexity | d018d1fbdb0a23e54f51d298beb7ede6 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /*
  2. CM.LatLng represents a geographical point with latitude and longtitude coordinates.
  3. */
  4. L.LatLng = function (/*Number*/ rawLat, /*Number*/ rawLng, /*Boolean*/ noWrap) {
  5. var lat = parseFloat(rawLat),
  6. lng = parseFloat(rawLng);
  7. if (isNaN(lat) || isNaN(lng)) {
  8. throw new Error('Invalid LatLng object: (' + rawLat + ', ' + rawLng + ')');
  9. }
  10. if (noWrap !== true) {
  11. lat = Math.max(Math.min(lat, 90), -90); // clamp latitude into -90..90
  12. lng = (lng + 180) % 360 + ((lng < -180 || lng === 180) ? 180 : -180); // wrap longtitude into -180..180
  13. }
  14. //TODO change to lat() & lng()
  15. this.lat = lat;
  16. this.lng = lng;
  17. };
  18. L.Util.extend(L.LatLng, {
  19. DEG_TO_RAD: Math.PI / 180,
  20. RAD_TO_DEG: 180 / Math.PI,
  21. MAX_MARGIN: 1.0E-9 // max margin of error for the "equals" check
  22. });
  23. L.LatLng.prototype = {
  24. equals: function (/*LatLng*/ obj) {
  25. if (!(obj instanceof L.LatLng)) {
  26. return false;
  27. }
  28. var margin = Math.max(Math.abs(this.lat - obj.lat), Math.abs(this.lng - obj.lng));
  29. return margin <= L.LatLng.MAX_MARGIN;
  30. },
  31. toString: function () {
  32. return 'LatLng(' +
  33. L.Util.formatNum(this.lat) + ', ' +
  34. L.Util.formatNum(this.lng) + ')';
  35. },
  36. // Haversine distance formula, see http://en.wikipedia.org/wiki/Haversine_formula
  37. distanceTo: function (/*LatLng*/ other)/*->Double*/ {
  38. var R = 6378137, // earth radius in meters
  39. d2r = L.LatLng.DEG_TO_RAD,
  40. dLat = (other.lat - this.lat) * d2r,
  41. dLon = (other.lng - this.lng) * d2r,
  42. lat1 = this.lat * d2r,
  43. lat2 = other.lat * d2r,
  44. sin1 = Math.sin(dLat / 2),
  45. sin2 = Math.sin(dLon / 2);
  46. var a = sin1 * sin1 + sin2 * sin2 * Math.cos(lat1) * Math.cos(lat2);
  47. return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  48. }
  49. };