Let $D \subset \mathbb{R}^{n}$ be a non empty convex closed set and:
$$f:\mathbb{R}^{n}\rightarrow \mathbb{R}_{+}, f(x)=(\operatorname{dist}(x,D))^{2}$$
Prove that f is differentiable in $\mathbb{R}^{n}$ and
$$f'(x)=2(x-P_{D}(x)), \forall x \in \mathbb{R}^{n},$$ where $\mbox{dist}(x,D)$ is the distance between a point $x$ and the set $D$ and $P_{D}(x)$ is the projection of $x$ in $D$, i.e.,
\begin{align} \operatorname{dist}\left(x, D \right) := \left\| x - P_{D}(x)\right\|_2. \end{align}
Here is a tedious but elementary proof.
Note that the projection is Lipschitz with rank one, that is $\|P_D(x)-P_D(y)\| \le \|x-y\|$ (see here for example).
Note that $f(y) \le \|y-P_D(x)\|^2 = \|x-P_D(x)+y-x\|^2 = f(x) + 2(x-P_D(x))^T(y-x) +\|y-x\|^2$ so we have $f(y)-f(x) - 2(x-P_D(x))^T(y-x) \le \|y-x\|^2$.
Swapping $x,y$ we get $-(f(y)-f(x) - 2(y-P_D(y))^T(y-x)) \le \|y-x\|^2$.
Note that $y-P_D(y) = x-P_D(x) + y-x+P_D(x)-P_D(y)$, so the above becomes \begin{eqnarray} -(f(y)-f(x) - 2(x-P_D(x))^T(y-x)) &\le & \|y-x\|^2-2(y-x+P_D(x)-P_D(y))(y-x) \\ &\le& 4 \|y-x\|^2 \end{eqnarray} In particular, $f$ is differentiable at $x$ and $D f(x)h = 2(x-P_D(x))^T h$.