lumnik. / scenarios All scenarios · Français

A sites export with broken GPS coordinates

Goal Read the GPS coordinates of a legacy export in decimal or in degrees-minutes-seconds, exchange a swapped pair, and empty every unusable point with its reason.

Dispatch takes over the delivery sites of a legacy ERP. Several tools typed the GPS points over the years:

The manifest makes one point per site, or says why there is none.

manifests/coordinates.kts
// Operator-provided: one delivery site's coordinates, as a legacy export wrote them, read as a GPS point.// Reads a decimal comma, a hemisphere letter (48.85 N, O 0.37) and degrees-minutes-seconds (48°50'12"N).// A pair it cannot trust is emptied, counted, and `coord_issue` says why. Nothing is guessed.@Suppress("UNCHECKED_CAST")val cells = bindings["cells"] as MutableMap<String, Any?>val context = bindings["context"] as Map<*, *>// The integrator's part. within: south, west, north, east — where the sites are. swapped: fix — exchange a swapped pair.val box = (context["within"] as List<*>?)?.map { (it as Number).toDouble() }require(box == null || (box.size == 4 && box[0] < box[2] && box[1] < box[3])) { "within: south, west, north, east" }require(context["swapped"] in setOf(null, "fix")) { "swapped: fix, or nothing" }val fixSwapped = context["swapped"] == "fix"// A cell as signed degrees, with the axis its hemisphere letter names (null: no letter).class Reading(val degrees: Double, val axis: String?)val letters = setOf("N", "S", "E", "W", "O")    // O: Ouest, as a French export writes Westval signed = Regex("""([+-]?)(\d+(?:[.,]\d+)?)""")fun decimal(text: String, signAllowed: Boolean): Double? {    val (sign, digits) = signed.matchEntire(text)?.destructured ?: return null    if (sign.isNotEmpty() && !signAllowed) return null    return digits.replace(',', '.').toDouble() * (if (sign == "-") -1 else 1)}fun whole(text: String) = text.takeIf { it.all(Char::isDigit) }?.toIntOrNull()// Degrees and minutes, seconds optional: 48°50'12", 43°42', 43 17 42.fun sexagesimal(parts: List<String>): Double? {    val degrees = whole(parts[0]) ?: return null    val minutes = whole(parts[1])?.takeIf { it < 60 } ?: return null    val seconds = if (parts.size == 3) decimal(parts[2], false)?.takeIf { it < 60 } ?: return null else 0.0    return degrees + minutes / 60.0 + seconds / 3600.0}fun read(raw: String): Reading? {    // Typographic marks and a no-break space, as a spreadsheet leaves them, read like the plain ones.    val text = raw.uppercase().replace('’', '\'').replace('′', '\'').replace('”', '"').replace('″', '"')        .replace(' ', ' ').trim()    val before = text.take(1).takeIf { it in letters }    val after = text.takeLast(1).takeIf { it in letters }    if (before != null && after != null) return null    val letter = before ?: after    val body = text.removePrefix(before ?: "").removeSuffix(after ?: "")    val parts = body.split(Regex("""[°'"\s]+""")).filter { it.isNotEmpty() }    val magnitude = when {        parts.size == 1 -> decimal(parts[0], signAllowed = letter == null)    // a letter comes instead of a sign        parts.size in 2..3 && letter != null -> sexagesimal(parts)        else -> null    } ?: return null    val axis = when (letter) { null -> null; "N", "S" -> "lat"; else -> "lon" }    return Reading(if (letter in setOf("S", "W", "O")) -magnitude else magnitude, axis)}fun inRange(lat: Double, lon: Double) = Math.abs(lat) <= 90 && Math.abs(lon) <= 180fun usable(lat: Double, lon: Double) =    inRange(lat, lon) && (box == null || (lat in box[0]..box[2] && lon in box[1]..box[3]))fun rounded(degrees: Double) = java.math.BigDecimal.valueOf(degrees).setScale(6, java.math.RoundingMode.HALF_UP)fun put(lat: Double?, lon: Double?, issue: String?) {    cells["lat"] = lat?.let(::rounded)    cells["lon"] = lon?.let(::rounded)    cells["coord_issue"] = issue}fun setAside(issue: String) {    put(null, null, issue)    (bindings["unreadable"] as Runnable).run()    // one pair, one count}fun exchanged(lat: Double, lon: Double) =    if (fixSwapped) put(lat, lon, "swapped: exchanged") else setAside("swapped")fun repair(rawLat: String, rawLon: String) {    if (rawLat.isEmpty() && rawLon.isEmpty()) return put(null, null, null)    // no point given: nothing to repair    if (rawLat.isEmpty() || rawLon.isEmpty()) return setAside("half a point")    val a = read(rawLat)    val b = read(rawLon)    if (a == null || b == null) return setAside("not a coordinate")    // What the letters say: 2.35 E under lat, or 48.85 N under lon, is a swapped pair.    val saysSwapped = a.axis == "lon" || b.axis == "lat"    val saysAsWritten = a.axis == "lat" || b.axis == "lon"    if (saysSwapped && saysAsWritten) return setAside("not a coordinate")    // two letters of one axis    val lettered = saysSwapped || saysAsWritten    val (lat, lon) = if (saysSwapped) b.degrees to a.degrees else a.degrees to b.degrees    when {        usable(lat, lon) -> if (saysSwapped) exchanged(lat, lon) else put(lat, lon, null)        // Without a letter, only the declared area can tell: the pair fits the other way round, and only that way.        !lettered && usable(lon, lat) -> exchanged(lon, lat)        inRange(lat, lon) || (!lettered && inRange(lon, lat)) -> setAside("outside the declared area")        else -> setAside("not degrees")    }}repair(cells["lat"]?.toString()?.trim().orEmpty(), cells["lon"]?.toString()?.trim().orEmpty())
sites.csv
site_id;name;city;lat;lon
S01;Entrepôt Gerland;Lyon;45.7302;4.8309
S02;Dépôt Villeurbanne;Villeurbanne;45,7719;4,8902
S03;Agence Bercy;Paris;48°50'12"N;2°22'58"E
S04;Plateforme Nantes;Nantes;47.2184 N;1.5536 W
S05;Agence Brest;Brest;48.3904;-4.4861
S06;Dépôt Marseille;Marseille;5.3698;43.2965
S07;Agence Lille;Lille;0;0
S08;Relais Toulouse;Toulouse;574357.82;6279642.97
S09;Agence Bordeaux;Bordeaux;;
S10;Dépôt Strasbourg;Strasbourg;48.5734;
S11;Relais Dijon;Dijon;n/a;n/a
S12;Agence Fort-de-France;Fort-de-France;14.6037;-61.0594
S13;Agence Rennes;Rennes;48°06'42"N;1°40'46"W
S14;Agence Tours;Tours;0.6848 E;47.3941 N
S15;Relais Reims;Reims;4.0317 E;49.2583
S16;Agence Caen;Caen;49.1829 N;O 0.3707
S17;Dépôt Nice;Nice;43°42'N;7°15'E
S18;Relais Pau;Pau;43 17 42 N;0 22 12 W
S19;Agence Metz;Metz;-49.1193 N;6.1757

… 2 more lines

manifests/20-site.yaml
kind: Entityname: delivery_site_clabel: Site de livraisondescription: "A delivery site with its GPS point in decimal degrees; coord_issue says why a point was set aside or exchanged."match: [site_id]scopes: [dispatch-c]columns:  site_id:    label: "Code site"  name:    label: "Site"  city:    label: "Ville"  lat:    label: "Latitude"  lon:    label: "Longitude"  coord_issue:    label: "Coordonnées: remarque"sources:  - table: t_scenario_sites_c    map:      site_id: site_id      name: name      city: city      lat: lat      lon: lon      coord_issue: coord_issue
manifests/30-sites-view.yaml
apiVersion: apps.lumnik.io/v1kind: Viewmetadata:  name: scenario-sites-cspec:  scope: dispatch-c  table: connector.v_delivery_site_c  title: Sites de livraison  columns: [site_id, name, city, lat, lon, coord_issue]  links:    - column: name      # tap a site: its point opens on a map, in a new tab      url: "https://www.openstreetmap.org/?mlat={lat}&mlon={lon}#map=16/{lat}/{lon}"
manifests/40-app.yaml
apiVersion: apps.lumnik.io/v1kind: Appmetadata:  name: scenario-dispatch-cspec:  title: Dispatch  scope: dispatch-c  icon: generic  theme:    accentColor: "#8b7ff0"    backgroundColor: "#14121f"  default: false

Limits

  • Without within, a swapped pair with no letter is not seen, and 0;0 is written as a point. Not replayed here.
  • One rectangle: the Fort-de-France site is a real point, outside mainland France, and it is emptied.
  • Lambert 93 metres are not converted: the pair is emptied.
  • The remarks are the script's own words.
  • No distance, no route, no geocoding. The link was read in the page, not followed.
  • Synthetic sites.

Logistics · delivery sites

Where exactly is this site?

The export writes it many ways.

Comma, degrees-minutes-seconds, N, E, O letters, a swapped pair, 0;0.

Synthetic sites

The problem

A wrong point looks like a right one.

  • 5.3698;43.2965: Marseille, the wrong way round.
  • 0;0: a real point, off the coast of Africa.
  • 574357.82: metres, not degrees.

Nothing is modified

The export stays as it is.

  • A script reads each pair.
  • The manifest says where the sites are.
  • A doubtful point is emptied, with its reason.

What had to be written

context:
  within: [41.0, -5.5, 51.5, 10.0]
  swapped: fix

The rectangle the sites live in.

The whole scenario is 4 declaration files, 72 lines, and a 98-line script.

The answers

21 sites written, 13 usable points.

  • 48°50'12"N becomes 48.836667.
  • 3 swapped pairs put the right way round, and flagged.
  • 7 pairs emptied, each with its reason.

The limit

The rectangle is the integrator's.

  • Without it, a swapped pair passes.
  • Fort-de-France is outside the rectangle.
  • Metres are not converted.

Try it

The scenario replays end to end.

A script, a connector, an entity, a view: each step is published with its output.

This scenario runs on lumnik Open, free and open source.

Try lumnik Open →