Heartworms are spread through a bite of a mosquito meaning that if the dog gets bitten by a mosquito then that's how the dog gets the heartworm.
If the dog isn't bitten by a mosquito then the dog won't develop heartworms.
Heartworms are not contagious to other dogs but you should give the dog heartworm medicine to prevent heartworms in case the dog gets bitten by a mosquito.