How can I position a node in the center of an arbitrary path

The pos option (or midway) referres alway to the last two given coordinates, i.e. in a path (0,0) -- (1,2) -- (3,-1) with the node at the end it will be centered on the line between (1,2) and (3,-1):

\documentclass{article}

\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
    \draw (0,0) -- (1,2) -- (3,-1) node [pos=0.5, fill=red] {x};
\end{tikzpicture}
\end{document}

centered node

To center a node in a shape with more edges you may use a hint: Create the path and then let a node fit all it’s coordinates (using the fit library). The content of this node will be centered in a rectangle (add draw=red to the node to see it) surrounding all given coordinates:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{fit}

\begin{document}
\begin{tikzpicture}
    \draw (-1,2) -- (5,2) -- (3,0) -- (0,0) -- cycle;
    \node [fit={(-1,2) (5,2) (3,0) (0,0)}] {x};
\end{tikzpicture}
\end{document}

rectangle fit

In some cases it could be an alternativ to use the shape library and set the dimensions to a node instead of using coordinates. To get the exact dimensions use inner sep=0pt additionally, otherwise the size will be advanced by the value of inner sep, which is 0.3333em ba default

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes.geometric}

\begin{document}
\begin{tikzpicture}
    \node [minimum width=2cm, minimum height=1cm,draw] {x};
    \node at (3,0) [minimum width=2cm, minimum height=1cm,draw,trapezium] {x};
    \node at (6,0) [minimum width=2cm, minimum height=1cm,draw,ellipse] {x};
\end{tikzpicture}
\end{document}

use node shapes

When you use a node it is even possible to align another node on top of it by giving the first one a name:

\documentclass{article}

\usepackage{tikz}
\usetikzlibrary{shapes.geometric}

\begin{document}
\begin{tikzpicture}
    \node (my node) [minimum width=2cm, minimum height=1cm,draw] {x};
    \node at (my node) [minimum width=1cm, minimum height=1cm,draw,circle] {X};
\end{tikzpicture}
\end{document}

anchoring named nodes


I was trying to do something similar and ended up finding this question.

But I found a different solution for the case where your path is polygonal (i.e., formed by straight lines connecting points): Give a name to every vertex in your path (say using coordinate), and latter use a barycentric coordinate system and create a node with weight one for each point in the path. That is the center of mass. Bellow is a minimal example.

\documentclass{standalone}
\usepackage{pgf,tikz}
\begin{document}
\begin{tikzpicture}
    \draw(0,0) coordinate (P1) -- (1,2) coordinate(P2) -- (3,-1) coordinate(P3) -- (2,-1) coordinate (P4) -- cycle;%%the cycle here does not affect the position of X.

    \coordinate (center) at (barycentric cs:P1=1,P2=1,P3=1,P4=1) {};
    \node at (center) {X};
\end{tikzpicture}
\end{document}

center of mass