Distance formula function with Flux and Grafana

I am currently working this project on NASA and I need to figure out how to create a distance formula function in Flux that pulls data from InfluxDB and calculates the distance formula for each metric of the displacement of the location from the initial location from when the test started and the current location of the test. Anyone have any useful help/information for me? I would appreciate your help greatly.

Thanks!

@themoonman How are the locations determined? Longitude and latitude?

Yes correct. x=longitude, y=latitude

Ok, what version of InfluxDB are you using? What is the schema of your data?

X-Influxdb-Version: v2.7.6

Schema:
-measurements: (many strings of the format: calendar_date_String)

  • tag keys: _field, _measurement, _start, _stop)
  • latitude field: r[“_field”] == “Iatitude”
  • longitude field: r[“_field”] == “longitude”

@themoonman Perfect. Thanks. Last question and then I should be able to give you an example of what you need. Are you looking to compute the distance between two specific points per query, or does the query need to calculate the distance between multiple pairs of geographic points? If the latter, how are the points associated or how do you know what points to pair together?

I am looking to compute the distance between two specific points per query.
-The very first query coordinates (latitude and longitude)
-The most recent query coordinates (latitude and longitude)

I just need the distance between these two points on a stat panel to update in real time.

Ok, this solution assumes a straight line between the first and last points (“as the crow flies”), but if you need to calculate the total distance travelled, that’s possible too (just let me know if that’s what you need).

import "array"
import "experimental/geo"

// Return the base data set.
data = () => 
    from(bucket: "example-bucket")
        |> range(start: -30d)
        |> filter(fn: (r) => r._measurement == "example-measurement")
        |> filter(fn: (r) => r._field == "longitude" or r._field == "latitude")

// Return a record with the first longitude and latitude values.
firstCoordinate =
    data()
        |> first()
        |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
        |> findRecord(fn: (key) => true, idx: 0)

// Return a record with the last longitude and latitude values.
lastCoordinate = data()
        |> last()
        |> pivot(rowKey: ["_time"], columnKey: ["_field"], valueColumn: "_value")
        |> findRecord(fn: (key) => true, idx: 0)

// Calculate the distance between the first and last coordinates.
distance = geo.ST_Distance(
    region: {lat: firstCoordinate.latitude, lon: firstCoordinate.longitude},
    geometry: {lat: lastCoordinate.latitude, lon: lastCoordinate.longitude},
)

// Build an ad hoc table with the distance value.
array.from(rows: [{_value: distance}])