write the conversion for pss68 in javascript

PSS68 is a formula used to convert between GPS coordinates (WGS84) and British Grid Coordinates. Here's an implementation of the formula in JavaScript:

index.tsx
function pss68(lat, lng) {
  // Convert to radians
  lat = lat * Math.PI / 180;
  lng = lng * Math.PI / 180;
  
  // Constants for PSS68 formula
  const a = 6377563.396;
  const b = 6356256.909;
  const e2 = 1 - (b * b) / (a * a);
  const n = (a - b) / (a + b);
  const n2 = n ** 2;
  const n3 = n ** 3;
  const n4 = n ** 4;
  const n5 = n ** 5;
  
  // Constants for British National Grid
  const phi0 = 49 * Math.PI / 180;
  const lambda0 = -2 * Math.PI / 180;
  const E0 = 400000;
  const N0 = -100000;
  const F0 = 0.9996012717;
  
  // PSS68 formula
  const nu = a * F0 / Math.sqrt(1 - e2 * Math.sin(lat) ** 2);
  const rho = a * F0 * (1 - e2) / Math.pow(1 - e2 * Math.sin(lat) ** 2, 1.5);
  const eta2 = nu / rho - 1;
  const M = b * F0 * ((1 + n + 1.25 * (n2 + n3) + 1.3125 * (n4 + n5)) * (lat - phi0)
            - 0.375 * (n2 + n3 + 0.9375 * (n4 + n5)) * Math.sin(2 * lat)
            + 0.0625 * (n3 + n4 + 0.46875 * n5) * Math.sin(4 * lat)
            - 0.010417 * n4 * Math.sin(6 * lat));
  const x = M + nu / 2 * Math.sin(lat) * Math.cos(lat) * (lng - lambda0) ** 2
          + nu / 24 * Math.sin(lat) * Math.cos(lat) ** 3 * (5 - Math.tan(lat) ** 2 + 9 * eta2) * (lng - lambda0) ** 4
          + nu / 720 * Math.sin(lat) * Math.cos(lat) ** 5 * (61 - 58 * Math.tan(lat) ** 2 + Math.tan(lat) ** 4) * (lng - lambda0) ** 6;
  const y = nu * Math.cos(lat) * (lng - lambda0)
          + nu / 6 * Math.cos(lat) ** 3 * (nu / rho - Math.tan(lat) ** 2) * (lng - lambda0) ** 3
          + nu / 120 * Math.cos(lat) ** 5 * (5 - 18 * Math.tan(lat) ** 2 + Math.tan(lat) ** 4 + 14 * eta2 - 58 * Math.tan(lat) ** 2 * eta2) * (lng - lambda0) ** 5;
          
  // Convert to OS grid
  const N = N0 + y;
  const E = E0 + x;
  
  return { easting: E, northing: N };
}
1760 chars
44 lines

You can use this function like so:

index.tsx
const result = pss68(51.5074, -0.1278); 
// { easting: 530047, northing: 180534 }
82 chars
3 lines

This will convert the GPS coordinates of London (latitude 51.5074, longitude -0.1278) to British Grid Coordinates (easting 530047, northing 180534).

related categories

gistlibby LogSnag