Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/turf-midpoint/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { bearing } from "@turf/bearing";
import { destination } from "@turf/destination";
import { distance } from "@turf/distance";
import { Coord } from "@turf/helpers";
import { getCoord } from "@turf/invariant";

/**
* Takes two points and returns a point midway between them. The midpoint is
Expand All @@ -28,6 +29,14 @@ function midpoint(point1: Coord, point2: Coord): Feature<Point> {
const heading = bearing(point1, point2);
const midpoint = destination(point1, dist / 2, heading);

// Interpolate altitude (z-coordinate) when both input points carry one.
// destination() propagates only the origin's z unchanged; average them instead.
const coord1 = getCoord(point1);
const coord2 = getCoord(point2);
if (coord1[2] !== undefined && coord2[2] !== undefined) {
midpoint.geometry.coordinates[2] = (coord1[2] + coord2[2]) / 2;
}

return midpoint;
}

Expand Down
1 change: 1 addition & 0 deletions packages/turf-midpoint/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
"@turf/destination": "workspace:*",
"@turf/distance": "workspace:*",
"@turf/helpers": "workspace:*",
"@turf/invariant": "workspace:*",
"@types/geojson": "catalog:",
"tslib": "catalog:"
}
Expand Down
31 changes: 31 additions & 0 deletions packages/turf-midpoint/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,3 +68,34 @@ test("midpoint -- long distance", function (t) {

t.end();
});
test("midpoint -- interpolates altitude (z-coordinate) from 3D points", function (t) {
var pt1 = point([0, 0, 100]);
var pt2 = point([10, 0, 200]);

var mid = midpoint(pt1, pt2);
var coords = mid.geometry.coordinates;

// The midpoint of two 3D points must interpolate z as the average
t.equal(
coords[2],
150,
"z should be the average of the two input altitudes (100+200)/2 = 150"
);

t.end();
});

test("midpoint -- returns undefined z when inputs have no altitude", function (t) {
var pt1 = point([0, 0]);
var pt2 = point([10, 0]);

var mid = midpoint(pt1, pt2);

t.equal(
mid.geometry.coordinates[2],
undefined,
"z should be undefined when inputs have no altitude"
);

t.end();
});
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading