[Tex/LaTex] Tikz: Calculate and store the Euclidian distance between two coordinates

calculationscoordinatestikz-pgf

Is there an easy way to store the Euclidian distance between two coordinates?

I want to store the value 4 in a macro, so that I can use it to specify the width of a node.

The easiest way I could think of to to this is to somehow store the output of veclen(x,y) to a macro. I found this line in the tikz-pgf manual

\pgfmathparse{veclen(12,5)} \pgfmathresult

but I can't get it to work.

Does anyone have an idea? I found a couple of answers in this site that have something to do with calculating the distance between coordinates, but they always use the distance inside a specific path and don't store it in a macro to use it later.

Best Answer

Here is a simple (?) code that computes the distance and stores it in a variable.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\makeatletter
\newcommand{\Distance}[3]{% % from https://tex.stackexchange.com/q/56353/121799
\tikz@scan@one@point\pgfutil@firstofone($#1-#2$)\relax  
\pgfmathsetmacro{#3}{round(0.99626*veclen(\the\pgf@x,\the\pgf@y)/0.0283465)/1000}
}% Explanation: the calc library allows us, among other things, to add and
% subtract points, so ($#1-#2$) is simply the difference between the points
% #1 and #2. The combination \tikz@scan@one@point\pgfutil@firstofone extracts
% the coordinates of the new point and stores them in \pgf@x and \pgf@y. 
% They get fed in veclen, and \pgfmathsetmacro stores the result in #3. 
% EDIT: included fudge factor, see https://tex.stackexchange.com/a/22702/121799
\makeatother
\begin{document}
\begin{tikzpicture}
\coordinate (X) at (1,0);
\coordinate (Y) at (3,0);
\draw[-] (X) -- (Y);
\node at (0,2) {\Distance{(X)}{(Y)}{\mylen}\mylen};
\end{tikzpicture}
\end{document}