Needles also was the first place train crews swapped out on freight trains headed east out of Los Angeles. That created hundreds of jobs.

But like many other small towns on the way to Los Angeles, Needles used to be a lot more important. The railroad cut the size of its train crews, and the elegant depot building in Needles is mostly empty. Needles lost its last grocery store in 2014. More than a quarter of the city’s residents live below the poverty line. Bit by bit, the jobs and the people were leaving.

In Mr. Williams’s first go-round as mayor from 2006 to 2010 (he was also a member of the City Council for four years), he tried to attract the solar industry. When that failed, he was drawn to the opportunity in marijuana by a friend who wanted to open a dispensary. California residents had voted to allow medical marijuana years earlier, in 1996.

Mr. Williams spoke with doctors about the potential benefits and slowly got over some of the antipathy toward the drug that his parents and his years as a police officer had instilled.

“It was like turning a battleship. It was a long process,” he said in a recent interview.

Mr. Williams, who said he still had not smoked marijuana himself, worked with the city manager and a lawyer to put together a ballot measure in 2012 that imposed a 10 percent tax on cannabis businesses. It passed with 81 percent of the vote.

“This is a very politically conservative town — but it’s got a streak of libertarianism,” Mr. Daniels, the city manager, said.

The first dispensaries in town still faced opposition, especially from local evangelical churches. But they have failed to attract the bad elements some expected. Crime has been stable over the last few years.