Jesus did not have to go through Samaria (in blue). In fact, most "good" Jews would have taken the path (in red) provided in this map. The reason is given in the text: "For Jews do not associate with Samaritans" (John 4:9). Here's a good explanation of what's going on here from Ray Pritchard (link to full article):
In Jesus’ day there were three regions stacked on top of one another. There was Galilee in the north, Samaria in the middle, and Judea in the south. The easiest and quickest way to get to Galilee from Judea was to go due north right through Samaria. John 4:4 says that Jesus “had to” go through Samaria. Now why did he have to do that? The answer is, he didn’t. There was another route he could have taken. Some pious Jews would go east, cross the Jordan River, enter the region of Perea, then go north, re-cross the Jordan River, and they would be in Galilee. This was out of the way but it meant they wouldn’t have to go through Samaritan territory.
A little history will help us at this point. The Jews and the Samaritans disliked each other. It all went back to 722 B.C. when the Assyrians conquered Israel and took the northern ten tribes into captivity. They brought in Gentiles from other areas to settle in that same region. Eventually those Gentiles with their pagan ways intermarried with the Jews who had been left behind. Over the generations those people were called the Samaritans, and they developed their own religion that was partly based on pagan ideas and partly based on Judaism. Eventually they built their own temple at a place called Mount Gerizim. And they developed their own language and their own version of the Old Testament (which contained only the first five books).
That brings us back to verse 3. Why did Jesus “have to” go through Samaria when the Jews either didn’t go there at all or passed through as quickly as possible? The answer is simple and profound: Jesus went because he intended to meet the woman at the well. He knew she would be coming to the well at precisely the moment he was sitting there weary from his journey. Nothing happens by chance in this story. Every detail is part of the outworking of God’s will. And that, I think, is a hugely important point. The woman isn’t looking for Jesus. All she wants is water. But Jesus is looking for her. You have to go to Samaria if you want to reach Samaritans. He doesn’t avoid Samaria and he doesn’t hurry through it. Though she does not know it, this woman has a “divine appointment” with the Son of God.