There are multiple ways to answer this question, but the heart of it all boils down to phrasing. You have to learn how to feel groups of 2 and 4 bar phrases. 95% of music breaks down into 2 or 4 bar phrases. When you begin studying a tune and internalizing the melody (a must), you can also analyze it's phrase structure. Practice the phrases individually. THEN practice improvising over that phrase over and over and over, until you have internalized what it feels like. Then go to the next phrase and repeat the same process. Once you complete those 2 phrases and feel comfortable, you put them together and practice it that way. Making sure to play the melody over the 2 phrases and then improvise. Switch between the 2...melody, improv, melody, improv and so forth. Then go onto the 3rd phrase and then the 4th. then chain them together and then chain all 4 together.
When you first start chaining your phrases together to improvise over them, be very diligent to utilize ideas that begin and end within each phrase. In other words, don't play over the bar lines, use any asymmetrical phrasing and or meander around. Be very specific and precise. When you have a Handel on it and feel the phrases easily you can work on the extra stuff
This is a long process and will take you anywhere from a week to a month to do it correctly, but in the end you will truly know the tune and you will never get lost again.
Of course ear training and other things are a definite must too, but the above method will really get you into the song intimately and that's what you want.
***What every you do, DON'T ever rely on a rhythm section to keep your place. EVER. Of course even the best turn themselves around and have to take a second to hear where they are, but that is a completely different thing than relying on the RS to keep your place.***