It's caused because the Cowper's gland, responsible for the erection, and lubrication from the penis, is situated next to the bladder. If a man lies down, and his bladder fills during the night, the full bladder presses on the Cowper's gland and gives an involuntary erection. It usuallly subsides when the man stands up, and the bladder moves off the gland, but if the bladder is really full, it can keep the erection, which will only subside when the bladder is empty - something of a 'Catch 22' sitation, since the penis is now pointing the wrong way to urinate! A little careful re-direction starts the urine flow, and the erection subsides almost imediately.
I used to get the 'morning glory' in my teens and twenties, but only very occasionally now I'm in my fifties.