ISTANBUL — President Recep Tayyip Erdogan of Turkey suffered the biggest defeat of his political career on Sunday as his candidate for Istanbul mayor conceded defeat in a repeat election.
The result in the do-over — held after Mr. Erdogan’s party lost and contested the first vote — wrests control over Turkey’s largest city from Mr. Erdogan and ends his party’s 25-year dominance there. Opponents say such a loss cracks the president’s aura of invincibility, showing that his grip on power after 16 years is weakening.
The defeat also puts Mr. Erdogan in a diminished position at a time of tense relations with the United States and other countries as he heads to the Group of 20 summit meeting next week, where he is planning to have talks on the sidelines with President Trump to address various disagreements.
Two hours after polls closed, Mr. Erdogan’s preferred candidate, Binali Yildirim, conceded defeat on national television. Mr. Erdogan acknowledged the result an hour later.
“The national will was manifested today one more time,” the Turkish president said on Twitter. Referring to the opposition candidate, he wrote, “I congratulate Ekrem Imamoglu, who won the election, according to unofficial results.”
The ANKA news agency reported that with all votes counted, Mr. Imamoglu led with 54 percent, compared with 45 percent for Mr. Yildirim. The semiofficial Anadolu Agency showed a similar result with 99 percent of the votes counted.
“As of now, my competitor Imamoglu is leading,” Mr. Yildirim said in his concession speech on television. “I congratulate him, wish him success. I wish our friend Ekrem Imamoglu will bring good services to Istanbul.”
Officials from the main opposition party, the People’s Republican Party, said they did not expect Mr. Erdogan’s party to challenge the result at the High Election Council because Mr. Yildirim had conceded so early.
Appearing at a news conference on Sunday evening, Mr. Imamoglu said that “16 million Istanbul residents refreshed our belief in democracy and confidence in justice.”
He also called on Mr. Erdogan to work with him. “I am ready to work with you in harmony,” Mr. Imamoglu said. “I put myself up for that, and I announce this in front of all Istanbul people.”
In addition to acknowledging the result on Twitter, Mr. Erdogan, in other Twitter posts, sought to move the agenda beyond the election, saying he would be attending to foreign and domestic issues at the Group of 20 summit meeting, which will be in Osaka, Japan, and during a meeting with China, and at a South European and Balkans summit meeting.
He told international journalists last week that he thought his rapport with Mr. Trump should be enough to ease a disagreement over his purchase of the Russian S-400 missile system, and possibly avoid sanctions. But this election result could well change the dynamics of that meeting.
In Istanbul, opposition supporters whistled as they caught the results on their cellphones at outdoor cafes. A car raced through the streets with its horn honking, like after a soccer match.
Mr. Imamoglu celebrated late Sunday night before a huge crowd in the park of his home district, Beylikduzu, where he has served as mayor for the past five years. Families were out with small children, and groups broke out in dancing.
“We will build democracy in the city, we will build justice,” Mr. Imamoglu said. “Nobody’s lifestyle and how they dress is a concern for us. We came to embrace everyone.”
“I thank the president and my opponent who congratulated me,” he said. “We will make the nation embrace each other. We will succeed in this despite everything.”
The vote “shows democracy is resilient and elections still matter,” said Soner Cagaptay, the director of the Turkish Research Program at the Washington Institute for Near East Policy. “Imamoglu won with a landslide — a 10-point lead — even though Erdogan mobilized all the state resources in this election.”
The mood had been tense in Istanbul during the day as people voted.
“The cancellation of the vote was completely unlawful and illegal,” Hatice Eksioglu said of the earlier election. “I am certain that he will win, but I am afraid,” she said, referring to Mr. Erdogan.
Mr. Imamoglu, 49, was backed by an alliance of opposition parties, united by their rejection of Mr. Erdogan’s increasingly authoritarian grip on Turkey.
Mr. Imamoglu won the vote on March 31 by a small margin. But Mr. Erdogan’s Justice and Development Party, or A.K.P., contested the results, and the High Election Council ordered the do-over.
While Mr. Erdogan has acquired broad powers under a new presidential system and controls all of the levers of power, a degree of democracy has remained as he has always sought legitimacy through the ballot box and assured citizens of the integrity of the process.
Besides the blow to Mr. Erdogan’s image and prestige, the loss of Istanbul has practical political consequences, analysts said. The city is Mr. Erdogan’s home and political base, where he began his political career as mayor.
“Losing Istanbul would mean losing a significant revenue source for A.K.P.’s political machinery, ranging from subsidies to the party faithful to construction contracts and funds for pro-government media,” Asli Aydintasbas, a senior fellow with the European Council for Foreign Relations, said before the vote.
“It would set off a chain reaction that can herald early elections later this year or in 2020,” she said.
Former President Abdullah Gul and former Prime Minister Ahmet Davutoglu are both committed to breaking away and starting their own conservative movements, Ms. Aydintasbas said.
Ozgur Unluhisarcikli, the Ankara director for the German Marshall Fund of the United States, a research organization, predicted before the election that the A.K.P. would grudgingly accept the results. But he said the party would seek to manage the change of power in Istanbul by “hollowing out the powers of metropolitan mayors in time.”
Mr. Erdogan grew up in a working-class district on the Golden Horn in Istanbul and embarked on his political career as a popular and energetic mayor of the city in the 1990s.
The city has remained in the hands of his party ever since, and he transformed it with extensive infrastructure projects and grandiose signature constructions, including a vast hilltop mosque, high-rise towers and expanding suburbs.
But Mr. Erdogan’s popularity in Istanbul, which derived largely from delivering services to city residents, has waned in recent years as the construction boom has stalled and the economy has slipped into recession, although growth rebounded somewhat earlier this year.
Unemployment and inflation have angered Turkish voters and cost Mr. Erdogan several of the largest cities, including the capital, Ankara, in local elections in March.
“Erdogan lost his magic touch,” said Mr. Cagaptay, the analyst. “Erdogan was this politician who came from the other side of the tracks, representing the voice of the common man, the pious, the dispossessed, making this his brand for nearly two decades. That is gone.”
Mr. Imamoglu has been compared to a young Mr. Erdogan because he comes from the same Black Sea region known for its fighting spirit, and for his personable and energetic attitude. He won voters’ support by offering a clean and all-embracing administration, tapping into a general weariness with the governing party and complaints of corruption and cronyism.
He promised that municipal workers’ jobs would be secure and that his administration would be nonpartisan.
“Nothing sticks to Imamoglu,” Mr. Cagaptay said. “He became the new Erdogan.”
Mr. Yildirim has been a close ally of Mr. Erdogan’s throughout his career, holding posts like transportation minister and prime minister and, most recently, president of Parliament. He had seemed a reluctant candidate in the March campaign, but after the shock of losing, he adopted a new campaign style, meeting people on squares and in neighborhoods, and emphasizing his years of experience and knowledge.
The opposition faced an uneven playing field throughout both mayoral campaigns, with Mr. Erdogan maintaining control over the mainstream news media and blatantly using government and municipal resources to support his candidate.
A week before the election, the two candidates faced off in a live television debate — the first Turkey had witnessed in 17 years — though it did not seem to tip the balance definitively. Mr. Imamoglu remained narrowly ahead in the polls.
Tensions rose in the final days before Sunday’s vote as Mr. Erdogan excoriated the opposition candidate while never uttering his name, and blasted the Republican People’s Party as undemocratic and the source of years of discrimination against religiously conservative citizens.
“What we have been having since March is a psychological war,” Ilayda Kocoglu, a spokeswoman for the Imamoglu campaign, said ahead of Sunday’s vote.
On Thursday night, Mr. Erdogan ramped up the pressure, warning that even if the opposition candidate won the mayorship, legal action could remove him from office for an insult that Mr. Imamoglu allegedly made to a regional governor during a recent argument.
“If the justice decides, his mayorship will be revoked,” Mr. Erdogan said in a live television interview on Thursday night. Mr. Imamoglu has denied uttering any insult.
Both of the main campaigns fielded ranks of lawyers to watch the voting at every ballot box across the municipality. Opposition lawyers went through exhaustive training in the weeks before the election and were told to avoid arguments over the ballot box but to make written objections for every irregularity.
Lawyers from both campaigns said they had agreed on new lists of polling station officials, all certified public officials, to prevent a repeat of the accusations that caused the March 31 election to be annulled.