My best friend came to visit me a few days ago.
Because we live so far apart, we don't get to see each other very often.
Why not meet halfway?
The problem is the ocean between us, but we still tried to find a place between our locations.
And now the going gets tough...
First approach
Do we draw a straight line between our cities on a map?
Tempting... but only accurate if you think we live on a pizza.
The distance of the straight line (in red) appears to be less than the shortest path (in black).
If we look at the same paths on a globe, the conclusion is different.
In fact there's about a 1000km difference.
If I take a random flight on FlightRadar, guess what? It takes a similar route to the shortest one.
Code approach
We could have used a piece of paper and some equations, but we're developers, not mathematicians, so a bit lazy.
Letβs use a code editor and Rust to find the answer.
Setup
If you haven't already done so, install Rust
Create a new project and add geo dependency.
$ cargo init
$ cargo add geo
Geo is a Rust crate that offers a wide range of geodetic calculations.
Code
In src/main.ts
we will first declare two points, one for each city.
use geo::Point;
fn main() {
let my_location = Point::new(2.341882700675668, 48.877569833869785);
let my_friend_location = Point::new(-122.4374290818876, 37.75484272253979);
}
Note that when you use decimal coordinates 12.34, 5.67 (from Google Maps, for example)
12.34 represents Y-axis and 5.67 X-axis.
That's why they are inverted in thePoint::new(...)
parameters.
The Geo library gives us a simple method of calculating a point along a path between two existing points on an ellipsoidal model of the earth.
Basically it calculates the distance between two points and takes a point at a fraction of the path.
a b <- Two points
a-----------------------b <- Path between two points
----------------------- <- Distance
----------- <- Distance * 0.5
m <- Resulting point
use geo::Point;
fn main() {
let my_location = Point::new(2.341882700675668, 48.877569833869785);
let my_friend_location = Point::new(-122.4374290818876, 37.75484272253979);
let path_middle_point = my_location.geodesic_intermediate(&my_friend_location, 0.5);
println!(
"Path middle point coordinates:{0},{1}",
path_middle_point.y(),
path_middle_point.x()
);
}
$ cargo run
Compiling Halfway v0.1.0 (/home/halfway)
Finished dev [unoptimized + debuginfo] target(s) in 1.93s
Running `target/debug/halfway`
Path middle point coordinates:63.527604504102385,-69.97702841714288
Now we know where to meet!
Code more
In the next part we will write more code to visualize paths.
Top comments (0)