跪拜 Guibai
← Back to the summary

From TLE to Trajectory: Drawing the ISS Orbit in Cesium

Cesium Getting Started: How TLE Data Becomes an Orbit Line

The complete chain from two-line TLE data to the visible ISS orbit curve in a Cesium scene. Core dependencies are satellite.js (SGP4/SDP4 standard propagation model) and Cesium (coordinate transformation + rendering).

Demo address: https://github.com/beat-the-buzzer/cesium-demos

1. Overall flow

TLE text ──twoline2satrec
──▶ satrec  ──propagate
──▶  ECI position (km)  ──eciToEcf + Cesium.Cartesian3.fromElements
──▶  ECEF Cartesian (m)  ──Cesium Entity.Polyline rendering
──▶  Orbit curve

2. Step-by-step explanation

Step 1: TLE text → SatRec structure (satellite.js)

const issSatrec = satellite.twoline2satrec(ISS_LINE1, ISS_LINE2);

Input: Two lines of fixed-width 69-character TLE text. Example:

ISS (ZARYA)
1 25544U 98067A   25250.50000000  .00016717  00000-0  30717-3 0  9993
2 25544  51.6400  208.9163 0006703 118.3651 241.6834 15.50000000123456

Output: A SatRec object, internally containing:

Field Meaning Used?
jdsatepoch Julian day of TLE epoch ✓
inclo Inclination (radians) ✓
no Mean motion (rad/min), T = 2π/n is orbital period ✓
ecco Eccentricity for SGP4
nodeo Right ascension of ascending node for SGP4
argpo Argument of perigee for SGP4
mo Mean anomaly for SGP4
bstar B* atmospheric drag coefficient (fixed-width scientific notation, restored by twoline2satrec per spec) for SGP4
method 'n' (near-Earth SGP4) or 'd' (deep-space SDP4) auto-selected
error Propagation error code (None=0 means normal) can be used for validation

Step 2: Compute orbital parameters

function computeSatelliteParams(satrec: satellite.SatRec) {
  const periodMin = (2 * Math.PI) / satrec.no; // period
  const inclinationDeg = Cesium.Math.toDegrees(satrec.inclo); // inclination
  return { periodMin, inclinationDeg };
}
Value Source Formula Physical meaning
periodMin satrec.no mean motion (rad/min) 2π / n Time for one full orbit around Earth (Kepler's third law)
inclinationDeg satrec.inclo orbital inclination (radians) toDegrees(inclo) Angle between orbital plane and equatorial plane

Detailed expansion:

Period periodMin = 2π / no

no is the "mean motion n" from TLE Line 2, columns 53–63, in rad/min. Kepler's third law gives the relationship between n and semi-major axis a for circular orbits:

$n = \sqrt{\frac{\mu}{a^3}} \quad \Rightarrow \quad T = \frac{2\pi}{n}$

no is itself the reciprocal form of the period. For the ISS, no ≈ 0.0676 rad/min, corresponding to T ≈ 92.9 min.

Inclination inclination = toDegrees(inclo)

inclo is the orbital inclination (radians) parsed from TLE Line 2, columns 09–16, with range [0°, 180°]. This value is given directly in the TLE and does not need propagation; it is only converted from radians to degrees for panel display. ISS inclination ≈ 51.64°.

The period is used in later calculations: use the period to get the total orbital time, then divide by the number of sample points to get the time interval between sample points.

Step 3: Time advancement

function tick(now: number) {
  const dt = now - lastRealTime.value;
  lastRealTime.value = now;
  if (timePlaying.value) {
    simOffsetMs.value += dt * (timeScale.value - 1);
  }
}
function currentSimDate(): Date {
  return new Date(Date.now() + simOffsetMs.value);
}

Step 4: Orbit propagation (ECI position)

const pv = satellite.propagate(issSatrec, t);
// pv.position = { x, y, z }  // km, ECI (Earth-centered inertial)
// pv.velocity = { x, y, z }  // km/s, ECI

For each sample time t on the trajectory, propagate is called once. Internally satellite.js branches by the method in satrec:

method Model Applicable to
'n' SGP4 Near-Earth orbits (ISS 380 km falls in this category)
'd' SDP4 Deep-space orbits (GPS ~20200 km)

Key constraint: The return value is ECI coordinates (Earth-centered inertial, in km). satellite.js does not provide ECEF or geodetic coordinates; subsequent transforms must be done yourself.

Step 5: ECI → ECEF transformation

function eciKmToFixed(eci, gmst) {
  const ecf = satellite.eciToEcf(eci, gmst);
  return Cesium.Cartesian3.fromElements(ecf.x * 1000, ecf.y * 1000, ecf.z * 1000, new Cesium.Cartesian3());
}

satellite.eciToEcf(pos, gmst) performs a rotation around the Z axis:

$$ \begin{bmatrix} x_{ecf} \ y_{ecf} \ z_{ecf} \end{bmatrix}

\begin{bmatrix} \cos \theta & \sin \theta & 0 \ -\sin \theta & \cos \theta & 0 \ 0 & 0 & 1 \end{bmatrix} \begin{bmatrix} x_{eci} \ y_{eci} \ z_{eci} \end{bmatrix} $$

where θ = GMST (Greenwich Mean Sidereal Time), computed by satellite.gstime(date). GMST changes approximately linearly with time (about 15°/hour = Earth's rotation rate).

The key data conversion code computeOrbitPoints:

// ============ Orbit calculation ============
function computeOrbitPoints(): Cesium.Cartesian3[] {
  const now = currentSimDate(); // current simulation time, current time plus simulation offset

  // Use the GMST of the current moment for the entire trajectory → trajectory fixed in inertial frame, Earth rotates beneath it
  const gmstNow = satellite.gstime(now); // GMST at current moment, in radians, representing the current rotation angle of Earth
  const totalMs = periodMin * 60 * 1000 * orbitPeriods.value; // total orbital time, in milliseconds; periodMin is in minutes, orbitPeriods is number of periods; 2 means draw two orbits
  const samples = orbitSamples.value; // number of sample points
  const stepMs = totalMs / samples; // time interval per sample point, milliseconds

  const result: Cesium.Cartesian3[] = [];
  for (let i = 0; i <= samples; i++) { // input sample count is 721
    const t = new Date(now.getTime() - totalMs / 2 + i * stepMs); // compute time of current sample point, ms; centers current sample time on the orbit
    const pv = satellite.propagate(issSatrec, t); // compute position and velocity for current sample point, both 3D vectors
    if (!pv || !pv.position) continue;
    result.push(eciKmToFixed(pv.position as satellite.EciVec3<number>, gmstNow));
  }
  return result;
}

// Get current simulation time
function currentSimDate(): Date {
  return new Date(Date.now() + simOffsetMs.value);
}

/**
 * Convert satellite.js ECI position (km) to Earth-fixed ECEF (meters) using the given GMST.
 *
 * Key: use the GMST from [the same moment] for all sample points of the entire trajectory;
 * only then do you get the fixed orbital plane in the inertial frame at that moment (inertial-frame trajectory).
 * If each sample point used its own GMST, you would get an Earth-fixed trajectory (drifting with Earth's rotation).
 */
function eciKmToFixed(eci: satellite.EciVec3<number>, gmst: number): Cesium.Cartesian3 {
  const ecf = satellite.eciToEcf(eci, gmst); // key code for inertial-to-Earth-fixed transformation
  // satellite.js gives km, Cesium needs m
  return Cesium.Cartesian3.fromElements(ecf.x * 1000, ecf.y * 1000, ecf.z * 1000, new Cesium.Cartesian3()); // pass a new Cesium.Cartesian3 instance to avoid modifying original data
}

Step 6: Cesium Entity rendering

// Cache the last valid position from the previous frame: reuse it when propagation fails or returns invalid results, avoiding the satellite teleporting to Earth's center
let lastValidIssPosition: Cesium.Cartesian3 | undefined;

function computeIssPosition(): Cesium.Cartesian3 | undefined {
  const date = currentSimDate();
  const pv = satellite.propagate(issSatrec, date);
  if (!pv || !pv.position) return lastValidIssPosition;

  const pos = eciKmToFixed(pv.position as satellite.EciVec3<number>, satellite.gstime(date));
  // Orbital decay / beyond model validity can return NaN or Infinity; discard directly
  if (!Number.isFinite(pos.x) || !Number.isFinite(pos.y) || !Number.isFinite(pos.z)) {
    return lastValidIssPosition;
  }
  lastValidIssPosition = pos;
  return pos;
}


// Satellite current position (recomputed every frame via CallbackProperty)
// ============ Entity construction ============
function buildIssEntities(v: Cesium.Viewer) {
  // ISS current position (same GMST moment as trajectory, ensuring satellite always lies on inertial-frame trajectory)
  issEntity = v.entities.add({
    id: 'iss',
    name: ISS_NAME,
    position: new Cesium.CallbackProperty(
      () => computeIssPosition(),
      false,
    ) as unknown as Cesium.PositionProperty,
    point: {
      pixelSize: 9,
      color: issColor,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 1,
    },
    label: {
      text: ISS_NAME,
      font: '12px "SF Mono", Menlo, monospace',
      fillColor: Cesium.Color.WHITE,
      outlineColor: Cesium.Color.BLACK,
      outlineWidth: 2,
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      pixelOffset: new Cesium.Cartesian2(0, -18),
      show: showLabels.value,
    },
  });

  // Orbit line (recomputed every frame)
  v.entities.add({
    id: 'iss-orbit',
    polyline: {
      positions: new Cesium.CallbackProperty(() => computeOrbitPoints(), false) as unknown as Cesium.Property,
      width: 1,
      material: Cesium.Color.WHITE.withAlpha(0.35),
      clampToGround: false,
    },
  });
}

Why use CallbackProperty? Because polyline.positions is of type Property, and CallbackProperty invokes its callback before Cesium renders each frame, so the orbit and satellite update automatically with simulation time without manually changing positions. Type-wise, a double assertion as unknown as Cesium.Property is needed because Cesium 1.147.0's type definitions declare CallbackProperty as an independent class.

Running effect:

image.png

Comments

Top 1 of 3 from juejin.cn, machine-translated. The original thread is authoritative.

王三岁_

Great article, thanks for sharing.

亲亲小宝宝鸭

It's the slacking-off big shot [witty].

王三岁_  → 亲亲小宝宝鸭

[facepalm]