The Spanish were in California and other western states, Mexico was not, the US got the land from Spain.
Go re-read your history books. By 1846, Spain had no presence in any territory that is now part of the US. That area was part of Mexico in 1846. The Treaty of Guadalupe Hildago was concluded between the US and Mexico; Spain was not a party to it. This treaty ended the Mexican-American War in 1848 and called for MEXICO to cede the land that now comprises the Southwestern US, and called for the US to pay $15 million to the government of Mexico directly and for the US to pay $3.25 million on claims of US citizens against the Mexican government. Spain lost effective control over its viceroyality of New Spain in 1821 with the conclusion of the Treaty of Cordoba. Spain rejected the treaty and for a time refused to recognize Mexican independence. However, in 1836, Spain ratified the treaty of Santa-Maria Calatrava which legally recognized Mexico as independent. All of this occurred BEFORE the territory in question passed into US control in 1848, so it is not possible that Spain gave up the territory. It most certainly was ceded by Mexico to the US.