With the score tied in the ninth, Miami loaded the bases with one out, getting a bloop hit by Miguel Rojas, a walk to Yadiel Rivera, and, after Hunter Strickland replaced reliever Reyes Moronta (2-1), an infield single by J.B. Shuck.
Then, on a 3-1 pitch, Anderson hit a fly ball to center that was deep enough to score Rojas.
It was the first career walk-off RBI for Anderson, and the last play of the game was the only time the Marlins led all night.
Miami fell behind three times in the game and tied the score three times as well. Justin Bour went 2-for-4 with two score-tying RBIs.
Marlins reliever Drew Steckenrider (3-1) earned the win, pitching a scoreless ninth.
The last-place Marlins will go for a four-game sweep of the series on Thursday afternoon.
Neither starting pitcher earned a decision.
Giants rookie left-hander Andrew Suarez, who made a homecoming after pitching locally at Miami's Columbus High and the University of Miami, allowed five hits, two walks and two runs in five innings. He struck out three.
Miami left-hander Caleb Smith, who leads National League rookies with 83 strikeouts, threw a career-high 107 pitches and allowed three runs in 6 1/3 innings. His quality start also included eight hits, no walks and four strikeouts.
Smith got off to a rough start as the Giants scored two runs in the first. With one out, Buster Posey sent an opposite-field shot off the fence in right for a double. On the next pitch, Andrew McCutchen homered to dead center. It was his seventh homer of the season and his fourth in the past 10 games.
Miami tied the score in the fourth. Anderson drew a leadoff walk and J.T. Realmuto singled. Cameron Maybin singled, and Anderson scored easily when center fielder Gorkys Hernandez stumbled and fell after fielding the hit.
Realmuto scored on Lewis Brinson's single up the middle, which went off the glove of shortstop Brandon Crawford. Maybin tried to score the go-ahead run on the play, but Crawford recovered and threw a perfect strike to the plate to get him.
San Francisco took a 3-2 lead in the sixth as a Crawford opposite-field single started a one-out rally. Crawford raced to third on a Nick Hundley single over a left-side shift and scored on an Austin Jackson line-drive single to center.
Miami tied the score in the bottom of the sixth. Realmuto singled, advanced to second on a hit-and-run groundout and scored when Bour hit an 0-2 pitch for a single to center.
Facing hard-throwing reliever Tayron Guerrero, the Giants went back on top 4-3 in the seventh. Posey walked, advanced on a groundout and scored when Evan Longoria smacked a 101 mph Guerrero fastball to center for an RBI single.
Miami, though, tied the score 4-4 in the eighth. Anderson walked and scored on a two-out double by Bour, who hit a first-pitch fastball to deep center field.
--Field Level Media