andybezbozhny

JavaScript.geo

Aug 7th, 2012 (edited)
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function distance(from, to) {
  2.     let R = 6371000;
  3.     let dLat = (to.lat - from.lat).toRad();
  4.     let dLon = (to.lon - from.lon).toRad();
  5.     let lat1 = from.lat.toRad();
  6.     let lat2 = to.lat.toRad();
  7.  
  8.     let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
  9.     let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  10.  
  11.     return R * c;
  12. }
  13.  
  14. Number.prototype.toRad = function() {
  15.     return this * Math.PI / 180;
  16. }
  17.  
  18. function geo2polar(from, to) {
  19.     let p = {};
  20.     let x = to.lon - from.lon;
  21.     let y = to.lat - from.lat;
  22.  
  23.     p.r     = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
  24.     p.theta = 0;
  25.  
  26.     if (x > 0 && y >= 0) {
  27.         p.theta = Math.atan(y / x);
  28.     } else if (x > 0 && y < 0) {
  29.         p.theta = Math.atan(y / x) + 2 * Math.PI;
  30.     } else if (x < 0) {
  31.         p.theta = Math.atan(y / x) + Math.PI;
  32.     } else if (x == 0 && y > 0) {
  33.         p.theta = Math.PI / 2;
  34.     } else if (x == 0 && y < 0) {
  35.         p.theta = 3 * Math.PI / 2;
  36.     } else if (x == 0 && y == 0) {
  37.         p.theta = 0;
  38.     }
  39.  
  40.     return p;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment