In the case of Facebook, you either put this in your profile, or the kinds of pages and events that you like and interact with will give this away.
Not saying that it's not creepy, just that with the way we use the internet these days, it's not an epic feat for an advertiser to figure this out given the amount of data we put out there.
Actually in this case it's pretty easy. If you're gay and use dating apps, and didn't opt out of application usage history in your settings, the presence of those apps in your history will flag you as having that interest to advertisers. The google analytics get resold/repackaged, either directly or indirectly through data brokers, to Facebook. Facebook suddenly starts displaying ads for expensive mens' underwear.