Carlos Alvarado, Costa Rica’s centre-left presidential candidate, is set to be the country’s next leader after elections on Sunday.
Costa Rica’s electoral council made the announcement based on ballots from 91% of polling stations.
Mr Alvarado won 60% of the vote to his conservative opponent’s 39%, the near-complete count shows.
His rival Fabricio Alvarado (no relation) has conceded defeat.
Alvarado versus Alvarado
Carlos Alvarado, 38, is a former labour minister, ex journalist, novelist and sometime rock singer. He ran on a progressive platform under the slogan Elijo el futuro (I choose the future).
Fabricio Alvarado, 43, is an evangelical preacher, one-time TV journalist and Christian music singer. He was standing for the conservative National Restoration Party (PRN) and had vowed to defend “traditional values”.
In the first round, Fabricio Alvarado secured the most votes, but missed the number needed to win outright.
That left him facing Carlos Alvarado in a second round vote.
Poll predictions put the candidates neck-and-neck in the weeks leading up to voting day.
What were the election issues?
Points of debate included fears about Costa Rica’s national deficit and the unprecedented rise of its murder rate.
But the close-run contest pivoted on the debate over legalising same-sex marriage.
In January, the Inter-American Human Rights Court ruled that gay marriages should be recognised – a decision applied to all signatory nations of the American Convention on Human Rights.
Fabricio Alvarado strongly opposed the ruling. Carlos Alvarado backed it, and branded his opponent homophobic.
Will Grant, BBC Mexico and Central America Correspondent
With the result now irreversible, many Costa Ricans are breathing a huge sigh of relief. Plenty of voters weren’t necessarily in love with the ruling party’s candidate, Carlos Alvarado, but saw the idea of handing the presidency to his opponent – a former evangelical pastor who had railed against the “secular state” – as unthinkable.
In the end, the election hinged on one key topic: same-sex marriage. The evangelical conservative candidate, Fabricio Alvarado, was only able to secure around 40% of the vote as Costa Ricans sided with the centre-left former labour minister, and a degree of continuity in office.
The Central American nation has a tradition of political stability and it didn’t take long for the defeated candidate to concede an election which had been expected to be much closer.