[Tex/LaTex] Multiply defined label warnings when using Subcaption in a Tikz picture

cross-referencingsubcaptiontikz-pgfwarnings

In an earlier question, I asked how to create zoomed highlights of a larger image automatically. User Jake provided an excellent solution using TikZ. However, when subcaptions and hyperref are added to the mix, we start getting multiply defined label warnings. Can anyone help diagnose the simplified example below?

When I compile this, I get the warning Label 'test' multiply defined.

Code example, courtesy of Jake:

\documentclass{article} 
\usepackage{tikz} 
\usetikzlibrary{spy} 

\begin{document} 

\begin{figure}\centering 
        \begin{tikzpicture}[spy using outlines] 
                \node{\label{test} Testcontent}; 
                \spy on (0,0) in node (0,0); 
        \end{tikzpicture} 
\caption{Testfigure} 
\end{figure} 

\end{document}

Best Answer

As Martin pointed out, using spy means the picture gets processed several times, which means the label also gets defined several times.

One way to get around this is to keep the spy inside a scope, and place the nodes with the labels after this scope, e.g. using the fit library to place the "label" node on top of the original one.

\documentclass{article} 
\usepackage{tikz} 
\usetikzlibrary{spy,fit} 

\begin{document} 

\begin{figure}\centering 
\begin{tikzpicture}
    \begin{scope}[spy using outlines] 
        \node (testnode) {Testcontent}; 
        \spy[size=1cm,magnification=2] on (0,0) in node at (1.5,1); 
    \end{scope}
    \node [fit=(testnode),inner sep=0pt] {\label{test}};
\end{tikzpicture} 
\caption{Testfigure} 
\end{figure} 

\end{document}