From my experience, there are two ways you can go with this assuming the same setting is inevitable:
1. Believe that every trip is different and the bad trip was just a fluke. Likely you'll find that the nature of the trip does indeed change on a case-by-case basis, depending on your mood in particular.
2. Face the bad trip head on and come to terms with it. This means getting to the root of what makes it "bad" to begin with and realizing that even a bad trip is pretty cool.
In reality, it's best to do both of these things. Go into the trip with attitude (1) and be ready to enact attitude (2) if things go South. On the flip side, if you approach the presumably bad trip with the playfulness and curiosity of attitude (2), then you will find that you can always get something positive out of the trip, even if it's the type of trip you would've considered bad before.
So my answer is that meditation can help, and my recommendation is that you meditate on (1) and (2) during the trip. Otherwise, I guess the trivial solution is to avoid the setting that caused the bad trip, in which case you might as well go for the exact opposite setting: day/night, indoors/outdoors, alone/with friends. And also, it can't hurt to change setting during the trip if you feel things are taking a negative turn, though you shouldn't drive while under the influence.
Every day I am thankful that I was introduced to psychedelic drugs.