I do it the same way a singer learns to sing a song that they've heard on the radio or cd. A singer knows which notes to sing, because he/she is familiar with the location of the notes in thier vocal range. Likewsie, we musicians have to know the location of the notes on the keyboard
But that takes a
whole lot of practice to master that. (I used to pactice for like 20 hrs a week)
You also have to know all of the major scales, that will make it easier to know which key you're in.
When I started out, I would just play the melody. As I've grown, I've learned to play chords and harmony parts. Now I'm trying to learn how to play the correct bass notes, which I have a problem hearing.