The tricky part is to find the nearest point on a meridian to a given point P. Let's fix the meridian M at φ=0, to keep the algebra simple.
Suppose P has spherical coordinates (θ, φ), with 0 ≤ θ ≤ π and -π < φ ≤ π. Let C be the great circle through P which is perpendicular to M; then we are looking for an intersection of C and M. (There are two such intersections; in the end we will simply choose the one that is on the same side of the equator as P).
The normal of C meets the sphere on the meridian M, at A = (ρ, 0), say. P is on C, so OP is perpendicular to OA, where O is the centre of the sphere. In cartesian coordinates, with r = 1 for simplicity:
A = (sin ρ, 0, cos ρ)
P = (cos φ sin θ, sin φ sin θ, cos θ)
The scalar product is
A.P = sin ρ cos φ sin θ + cos ρ cos θ
This must be zero, giving
tan ρ = -1/(cos φ tan θ)
The required point, Q say, is on M and perpendicular to A, so if Q = (σ, 0) in spherical coordinates, we have
tan σ = -1/tan ρ = cos φ tan θ
Q = (arctan (cos φ tan θ), 0)
If this Q is on the wrong side of the equator, take
Q = (-arctan π - arctan (cos φ tan θ), π)