[President Erdogan will have his hands full in containing the fallout from the electoral defeat.]

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.”

Mr. Imamoglu won the first vote in the mayoral race, 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.

In addition to acknowledging Sunday’s 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.

The mood had been tense in Istanbul during the day as people voted. But later, opposition supporters whistled as they caught the results on their cellphones at outdoor cafes. A car raced through the streets, honking its horn as if celebrating after a soccer match.