We show that the eccentricities, diameter, radius, and Wiener index of an undirected n-vertex graph with nonnegative edge lengths can be computed in time O(n⋅(kk+⌈logn⌉)⋅2kk2logn), where k is the treewidth of the graph. For every ϵ>0, this bound is n1+ϵexpO(k), which matches a hardness result of Abboud, Vassilevska Williams, and Wang (SODA 2015) and closes an open problem in the multivariate analysis of polynomial-time computation. To this end, we show that the analysis of an algorithm of Cabello and Knauer (Comp. Geom., 2009) in the regime of non-constant treewidth can be improved by revisiting the analysis of orthogonal range searching, improving bounds of the form logdn to (dd+⌈logn⌉), as originally observed by Monier (J. Alg. 1980). We also investigate the parameterization by vertex cover number