GPS Calculation Guide

GPS Calculation Guide

Motivation

Many systems have data stored in GPS coordinates (latitude, longitude). To be able to integrate and showcase them in twinzo - Digital Twin platform, they need to be recalculated to local twinzo coordinates. This guide will show you how.

GPS items creation

In the twinzo portal go to bookmark Places/GPS items (documentation here). Without knowing where North is on the layout, you need at least 3 GPS items with x, y, lat, and lon Strong preference for the corners of the sector layout.

GPS items download

Here is a screenshot from Postman, showing how to get GPS items downloaded to your software. Three important parameters are Client, Branch, and Api-Key. If you are missing any of them please ask your contact person to provide them.

GPS item data structure

In the coming steps, we will show you examples from our Kotlin language implementation of a data structure and calculation.

GpsItem( @SerializedName("id") var id: Int? = null, @SerializedName("lat") var latitude: Double? = null, @SerializedName("lon") var longitude: Double? = null, @SerializedName("timestamp") var timestamp: Long? = null, @SerializedName("x") var X: Float? = null, @SerializedName("y") var Y: Float? = null, @SerializedName("distance") var distance: Double? = null )
class MyPoint extends Point{ MyPoint({required double x, required double y}): super (x, y); double angleTo(MyPoint in2){ return Vector2(this.x as double, this.y as double).angleTo(Vector2(in2.x as double, in2.y as double)); } MyPoint centerOfLineTo(MyPoint in2){ return new MyPoint( x: ((this.x + in2.x) / 2) * 1.0, y: ((this.y + in2.y) / 2) * 1.0 ); } }

GPS coordinates recalculation to twinzo coordinates

Now, with the established data structure we are ready to continue with the trilateration.

Distance from GPS item (myGpsItem contains my position in lat, lon only)

fun calculateDistanceForGpsItems(myGpsItem: GpsItem, GpsBeacons: ArrayList<GpsItem>) = runBlocking { var result: ArrayList<GpsItem> = ArrayList() for (item in GpsBeacons) { item.distance = distanceToGpsItems(myGpsItem.latitude!!, myGpsItem.longitude!!, item.latitude!!, item.longitude!!) * 1000 result.add(item) } result } fun distanceToGpsItems(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { val R = 6371000 // metres val fi1 = Math.toRadians(lat1) val fi2 = Math.toRadians(lat2) val deltafi = Math.toRadians(lat2 - lat1) val deltalambda = Math.toRadians(lon2 - lon1) val a = Math.sin(deltafi / 2) * Math.sin(deltafi / 2) + Math.cos(fi1) * Math.cos(fi2) * Math.sin(deltalambda / 2) * Math.sin(deltalambda / 2) val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)) val distance = R * c return distance }

Positioning Item

A little more of mathematics ahead of us.

class PositioningItem extends Equatable { MyPoint point; double? distance; List<MyPoint> getIntersectionsWith(PositioningItem inPositionigItem) { PositioningItem inPosItem = new PositioningItem(point: inPositionigItem.point, distance: inPositionigItem.distance); PositioningItem thisPosItem = new PositioningItem(point: this.point, distance: this.distance); List<MyPoint> result = []; double coefPlaceHolder = (thisPosItem.point.distanceTo(inPosItem.point) + thisPosItem.distance! + inPosItem.distance!) * (thisPosItem.point.distanceTo(inPosItem.point) + thisPosItem.distance! - inPosItem.distance!) * (thisPosItem.point.distanceTo(inPosItem.point) - thisPosItem.distance! + inPosItem.distance!) * (-thisPosItem.point.distanceTo(inPosItem.point) + thisPosItem.distance! + inPosItem.distance!); if(coefPlaceHolder < 0){ //points doesnt have intersections result.add(thisPosItem._getClosestTangentTo(inPosItem)); print("FLUTTER tang $thisPosItem ${inPosItem} ${result}"); return result; }else { double coef = 0.25 * sqrt(coefPlaceHolder); result.add(MyPoint( x: (thisPosItem.point.x + inPosItem.point.x) / 2 + ((pow(thisPosItem.distance!, 2) - pow(inPosItem.distance!, 2)) / (2 * pow(thisPosItem.point.distanceTo(inPosItem.point), 2)) * (inPosItem.point.x - thisPosItem.point.x) + (2 * coef * (inPosItem.point.y - thisPosItem.point.y)) / pow(thisPosItem.point.distanceTo(inPosItem.point), 2)), y: (thisPosItem.point.y + inPosItem.point.y) / 2 + ((pow(thisPosItem.distance!, 2) - pow(inPosItem.distance!, 2)) / (2 * pow(thisPosItem.point.distanceTo(inPosItem.point), 2)) * (inPosItem.point.y - thisPosItem.point.y) - (2 * coef * (inPosItem.point.x - thisPosItem.point.x)) / pow(thisPosItem.point.distanceTo(inPosItem.point), 2)) ) ); result.add(MyPoint( x: (thisPosItem.point.x + inPosItem.point.x) / 2 + ((pow(thisPosItem.distance!, 2) - pow(inPosItem.distance!, 2)) / (2 * pow(thisPosItem.point.distanceTo(inPosItem.point), 2)) * (inPosItem.point.x - thisPosItem.point.x) - (2 * coef * (inPosItem.point.y - thisPosItem.point.y)) / pow(thisPosItem.point.distanceTo(inPosItem.point), 2)), y: (thisPosItem.point.y + inPosItem.point.y) / 2 + ((pow(thisPosItem.distance!, 2) - pow(inPosItem.distance!, 2)) / (2 * pow(thisPosItem.point.distanceTo(inPosItem.point), 2)) * (inPosItem.point.y - thisPosItem.point.y) + (2 * coef * (inPosItem.point.x - thisPosItem.point.x)) / pow(thisPosItem.point.distanceTo(inPosItem.point), 2)) ) ); return result; } }

Position Calculation

Least Squares Multilateration Strategy

Overview

This code implements a 2D Multilateration algorithm using the Ordinary Least Squares (OLS) method. It is designed to calculate an unknown user position $(x, y)$ based on the known distances to at least three reference points (anchors/GPS nodes).

Because distance measurements in the real world are rarely perfect (due to signal noise or GPS inaccuracies), multiple circles rarely intersect at a single perfect point. This algorithm uses the least-squares approach to find the mathematically "best fit" position that minimizes the overall error across all available anchors.

It handles errors gracefully using the Either<Failure, Success> functional programming pattern, ensuring that math exceptions (like singular matrices) or bad data inputs are caught and propagated safely.

DISCLAIMER: This calculation method has its limitations due to not accounting for earth curvature. This is an optimization we decided to trade for the speed of calculation.

@override Future<Either<Failure, PositionModel?>> calculatePositionLeastSquaresPositionStrategy( PositioningItemsEntity inPoints) async { try { // Delegate the actual least-squares math to the helper method Either<Failure, PositionModel?> result = await _calculateLeastSquaresPosition(inPoints.posItems); // Handle Either return type (Failure | PositionModel?) return result.fold( (failure) { return Left(failure); // propagate failure }, (position) { return Right(position); // propagate success }, ); } catch (e) { // Catch-all safeguard in case something unexpected blows up return Left(GenericFailure(message: "GPS Least sqares pos strategy failed $e")); } } /// Core least-squares multilateration implementation. /// Works with 3 or more anchors (2D). Future<Either<Failure, PositionModel?>> _calculateLeastSquaresPosition( List<PositioningItemModel> inPoints) async { try { // We need at least 3 anchors to solve a 2D position if (inPoints.length < 3) { return const Left(GenericFailure( message: "At least 3 anchors (GPS items) required for 2D multilateration")); } // Use the first anchor as a reference point final x1 = inPoints[0].position.x; // in Millimeters final y1 = inPoints[0].position.y; // in Millimeters final r1 = inPoints[0].distance! * 1000; // convert km → meters if distances are in km // Build the linear system A·x = b final A = <List<double>>[]; // coefficient matrix final b = <double>[]; // constants vector // For each remaining anchor, generate one linear equation for (int i = 1; i < inPoints.length; i++) { final xi = inPoints[i].position.x; // in Millimeters final yi = inPoints[i].position.y; // in Millimeters final ri = inPoints[i].distance! * 1000; // convert km → meters if distances are in km // Coefficients for this row of A final ai = [2 * (xi - x1), 2 * (yi - y1)]; // Corresponding constant for this row of b final bi = r1 * r1 - ri * ri + xi * xi - x1 * x1 + yi * yi - y1 * y1; A.add(ai); b.add(bi); } // Solve least-squares: (AᵀA)⁻¹ Aᵀb final At = _transpose(A); // Aᵀ final AtA = _multiply(At, A); // AᵀA (2x2 matrix) final Atb = _multiplyVector(At, b); // Aᵀb (2x1 vector) final AtAInv = _invert2x2(AtA); // (AᵀA)⁻¹ final sol = _multiplyVector(AtAInv, Atb); // solution [x, y] // Return computed position return Right(PositionModel(x: sol[0], y: sol[1])); } catch (e) { return Left(GenericFailure(message: "Multilateration failed: $e")); } } /// --- Small linear algebra helpers --- /// Matrix transpose List<List<double>> _transpose(List<List<double>> m) { final rows = m.length, cols = m[0].length; final result = List.generate(cols, (_) => List.filled(rows, 0.0)); for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { result[j][i] = m[i][j]; } } return result; } /// Matrix multiplication (a × b) List<List<double>> _multiply(List<List<double>> a, List<List<double>> b) { final rowsA = a.length, colsA = a[0].length; final rowsB = b.length, colsB = b[0].length; if (colsA != rowsB) throw ArgumentError("Incompatible dimensions"); final result = List.generate(rowsA, (_) => List.filled(colsB, 0.0)); for (var i = 0; i < rowsA; i++) { for (var j = 0; j < colsB; j++) { for (var k = 0; k < colsA; k++) { result[i][j] += a[i][k] * b[k][j]; } } } return result; } /// Matrix-vector multiplication (a × v) List<double> _multiplyVector(List<List<double>> a, List<double> v) { final rows = a.length, cols = a[0].length; if (cols != v.length) throw ArgumentError("Incompatible dimensions"); final result = List.filled(rows, 0.0); for (var i = 0; i < rows; i++) { for (var j = 0; j < cols; j++) { result[i] += a[i][j] * v[j]; } } return result; } /// Inverse of a 2×2 matrix /// m = [ [a, b], /// [c, d] ] /// inv(m) = 1/det * [ [d, -b], /// [-c, a] ] List<List<double>> _invert2x2(List<List<double>> m) { if (m.length != 2 || m[0].length != 2) throw ArgumentError("Matrix is not 2x2"); final det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; if (det.abs() < 1e-9) throw ArgumentError("Matrix is singular (non-invertible)"); final invDet = 1.0 / det; return [ [m[1][1] * invDet, -m[0][1] * invDet], [-m[1][0] * invDet, m[0][0] * invDet] ]; }

If you encounter any issues or need assistance with using this product, please do not hesitate to reach out for support. Our team is here to help you resolve any problems and answer any questions you may have.
To create a support ticket, visit our support portal at https://partner.twinzo.eu/helpdesk/customer-care-1