can you implement this in java?
- User
can you implement this in java?
- Assistant
can you implement this in java?
Below is a self-contained “reference implementation” that shows the full pipeline:
android.location.GnssStatusThe code uses the open-source Orekit orbital mechanics library because it is
modern, actively maintained, and available on Maven Central.
If you prefer pure Java without external libs you would have to port/ship an
SGP4 implementation yourself – that’s 1-2 k LOC, so Orekit is usually the
simpler route.
────────────────────────────────────────────────────────
Gradle (Kotlin DSL)
dependencies {
implementation("org.orekit:orekit:12.0") // or the newest version
// Only needed at compile time, Orekit downloads no network data
// you point it to an orekit-data folder (see below).
}
Maven
<dependency>
<groupId>org.orekit</groupId>
<artifactId>orekit</artifactId>
<version>12.0</version>
</dependency>
Orekit needs an “orekit-data” directory with Earth orientation parameters,
gravity field, etc.
Download the pre-packaged zip from
https://gitlab.orekit.org/orekit/orekit-data
unzip beside your JAR or ship it in src/main/resources/orekit-data.
──────────────────────────────────────────────────────── 2. Java classes ────────────────────────────────────────────────────────
package demo.gnssmatching;
import org.orekit.Utils;
import org.orekit.bodies.GeodeticPoint;
import org.orekit.bodies.OneAxisEllipsoid;
import org.orekit.data.DataProvidersManager;
import org.orekit.data.DirectoryCrawler;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.TopocentricFrame;
import org.orekit.orbits.OrbitType;
import org.orekit.propagation.analytical.tle.TLE;
import org.orekit.propagation.analytical.tle.TLEPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.AngularCoordinates;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GnssMatcher {
// ---------- 1. tiny record for the observation coming from Android ----------
public static record Observation(
int svid, // as reported by GnssStatus
double azDeg, // clockwise from true north
double elDeg) { } // 0° horizon, 90° zenith
// ---------- 2. represent a match result ------------------------------------
public static record Match(
Observation obs,
TLE tle,
double angularSeparationDeg) { }
// ---------- 3. public API ---------------------------------------------------
/**
* @param tleFile local file with *all* GNSS TLEs (two-line format)
* e.g. “https://celestrak.org/NORAD/elements/gps-ops.txt”
* @param observerLLA {latDeg, lonDeg, heightMeters}
* @param epochUtcMs time of the Android measurement (System.currentTimeMillis())
* @param observations list of satellites exactly from the same epoch
* @param toleranceDeg match will be returned only if < toleranceDeg
*/
public static List<Match> matchGnss(
Path tleFile,
double[] observerLLA,
long epochUtcMs,
List<Observation> observations,
double toleranceDeg) throws Exception {
initOrekit(); // (only once per JVM)
OneAxisEllipsoid wgs84 = new OneAxisEllipsoid(
Constants.WGS84_EARTH_EQUATORIAL_RADIUS,
Constants.WGS84_EARTH_FLATTENING,
FramesFactory.getITRF(IERSConventions.IERS_2010, true));
GeodeticPoint gp = new GeodeticPoint(
Math.toRadians(observerLLA[0]),
Math.toRadians(observerLLA[1]),
observerLLA[2]);
TopocentricFrame topo = new TopocentricFrame(wgs84, gp, "observer");
AbsoluteDate date = new AbsoluteDate(
Instant.ofEpochMilli(epochUtcMs),
TimeScalesFactory.getUTC());
List<TLE> tles = loadTLEs(tleFile);
// Pre-compute az/el for every TLE at this instant
Map<TLE, double[]> tleAzElMap = new HashMap<>(tles.size());
for (TLE tle : tles) {
double[] azel = azEl(tle, date, topo);
tleAzElMap.put(tle, azel);
}
// Compare with every observation
List<Match> result = new ArrayList<>();
for (Observation obs : observations) {
double bestSep = Double.MAX_VALUE;
TLE bestTle = null;
// convert observation into unit vector
double[] uObs = toUnitVector(obs.azDeg, obs.elDeg);
for (TLE tle : tles) {
double[] azel = tleAzElMap.get(tle);
double[] uTle = toUnitVector(azel[0], azel[1]);
double sepRad = Math.acos(
uObs[0]*uTle[0] + uObs[1]*uTle[1] + uObs[2]*uTle[2]);
if (sepRad < bestSep) {
bestSep = sepRad;
bestTle = tle;
}
}
double sepDeg = Math.toDegrees(bestSep);
if (sepDeg <= toleranceDeg && bestTle != null) {
result.add(new Match(obs, bestTle, sepDeg));
}
}
return result;
}
// ---------- 4. helper: load all TLEs in file --------------------------------
private static List<TLE> loadTLEs(Path file) throws IOException {
List<String> lines = Files.readAllLines(file);
List<TLE> list = new ArrayList<>(lines.size() / 3);
for (int i = 0; i + 2 < lines.size(); i += 3) {
String l1 = lines.get(i + 1).trim();
String l2 = lines.get(i + 2).trim();
list.add(new TLE(l1, l2));
}
return list;
}
// ---------- 5. helper: propagate & compute az/el ----------------------------
private static double[] azEl(TLE tle, AbsoluteDate date, TopocentricFrame topo) {
TLEPropagator prop = TLEPropagator.selectExtrapolator(tle);
PVCoordinates pv = prop.getPVCoordinates(date, FramesFactory.getITRF(IERSConventions.IERS_2010, true));
// vector from observer to satellite in topocentric frame
PVCoordinates topoPv = topo.getTransformTo(FramesFactory.getITRF(IERSConventions.IERS_2010, true), date)
.transformPVCoordinates(pv);
AngularCoordinates ac = new AngularCoordinates(
topoPv.getPosition(),
topoPv.getVelocity(),
topoPv.getPosition().getNorm());
double az = Math.toDegrees(topo.getAzimuth(ac.getRotation().applyTo(topoPv.getPosition()), date));
double el = Math.toDegrees(topo.getElevation(ac.getRotation().applyTo(topoPv.getPosition()), date));
// Orekit returns az in [−180°, 180°] with 0° = North east-positive.
// Android wants [0°, 360°) clockwise from North. Convert:
if (az < 0) az += 360;
return new double[]{az, el};
}
// ---------- 6. helper: horizon coords → unit vector -------------------------
private static double[] toUnitVector(double azDeg, double elDeg) {
double az = Math.toRadians(azDeg);
double el = Math.toRadians(elDeg);
double cosEl = Math.cos(el);
double x = cosEl * Math.sin(az); // East (Android az 90°) ➜ X
double y = cosEl * Math.cos(az); // North (az 0°) ➜ Y
double z = Math.sin(el);
return new double[]{x, y, z};
}
// ---------- 7. initialise Orekit data once per JVM -------------------------
private static volatile boolean orekitInitDone = false;
private static synchronized void initOrekit() throws IOException {
if (orekitInitDone) return;
// locate orekit-data directory (adjust to your environment!)
Path orekitData = Path.of("orekit-data"); // sibling dir of your jar
if (!Files.exists(orekitData)) {
throw new IOException("orekit-data folder not found.");
}
DataProvidersManager manager = DataProvidersManager.getInstance();
manager.addProvider(new DirectoryCrawler(orekitData));
// turn off checks for missing data sets you don't need
Utils.setDataRoot(orekitData.toString());
orekitInitDone = true;
}
// ---------- 8. tiny demo ----------------------------------------------------
public static void main(String[] args) throws Exception {
// 1. download the up-to-date TLEs for all GNSS constellations in one file
// (for quick demo you can just cat the four individual files together)
Path tleFile = Path.of("gnss.tle");
// 2. your phone‘s location fix (decimal degrees + m)
double[] lla = { 37.4220, -122.0841, 10 }; // Googleplex
// 3. epoch of the GnssStatus callback
long now = System.currentTimeMillis();
// 4. observations (bring them from GnssStatus)
List<Observation> obs = List.of(
new Observation(3, 45.0, 55.0),
new Observation(5, 180.0, 25.0),
new Observation(7, 320.0, 35.0)
);
List<Match> matches = matchGnss(tleFile, lla, now, obs, 7.5); // 7.5° tolerance
for (Match m : matches) {
System.out.printf(
"Android SVID %d → NORAD %s (%.2f°)\n",
m.obs().svid(),
m.tle().getSatelliteNumber(),
m.angularSeparationDeg());
}
}
}
──────────────────────────────────────────────────────── 3. How do I feed the Android GnssStatus? ────────────────────────────────────────────────────────
public void onSatelliteStatusChanged(@NonNull GnssStatus status) {
List<GnssMatcher.Observation> list = new ArrayList<>(status.getSatelliteCount());
for (int i = 0; i < status.getSatelliteCount(); i++) {
if (!status.hasAlmanacData(i)) continue; // skip unhealthy sats
int svid = status.getSvid(i);
double az = status.getAzimuthDegrees(i);
double el = status.getElevationDegrees(i);
list.add(new GnssMatcher.Observation(svid, az, el));
}
// pass list + current device location + timestamp to matchGnss(...)
}
──────────────────────────────────────────────────────── 4. Tuning & caveats ────────────────────────────────────────────────────────
• Android az/el noise: ±2–5° is common, occasionally worse → keep tolerance generous (5-10°).
• Make sure the timestamp you send to matchGnss is exactly the epoch of the GNSS measurements; if you call System.currentTimeMillis() a few seconds later, the satellites will have moved.
• Download new TLEs at least every 24 h; GPS TLEs drift roughly 1–2 °/day in az/el.
• If two satellites are within the tolerance window, the function will return the one with the smallest separation; for professional use, add extra checks (C/N0, Doppler, pseudorange code, etc.).
• The conversion between Android and Orekit azimuth conventions is handled in toUnitVector() & azEl(). If you use a custom SGP4 implementation make sure to replicate that mapping.
────────────────────────────────────────────────────────
That’s it! Drop the two source files and the orekit-data folder in your
project and you can identify every GPS, GLONASS, Galileo, or BeiDou satellite
that the Android framework reports.