J.T. Realmuto had two hits and scored twice for the Marlins, who have won three straight for the first time since winning four in a row April 28-May 1.
Andrew McCutchen hit a two-run home run and Buster Posey had three hits for the Giants, who have lost four of five.
Reyes Moronta (2-1) allowed the first two hitters to reach in the bottom of the ninth, prompting manager Bruce Bochy to call on Hunter Strickland. Pinch-hitter J.B. Shuck hit a hard grounder down the first-base line, but Posey was able to dive to keep the ball in front of him, preventing the Marlins from scoring.
However, Strickland got himself into a 3-1 count against Anderson with one out. Anderson connected on a flyball to center field caught by Gorkys Hernandez, whose throw home was too late to catch Miguel Rojas.
It was the Marlins' third walk-off win of the season.
San Francisco's Evan Longoria broke a 3-all tie with a hit in the seventh off Tayron Guerrero. The Marlins responded with a two-out RBI double in the eighth by Justin Bour off Sam Dyson, tying the game at 4.
It was the third time in the game the Marlins trailed but bounced back to draw even.
Drew Steckenrider (3-1) pitched a scoreless top of the ninth.
Andrew Suarez allowed five hits and two runs in five innings for the Giants, pitching in his hometown in front of a number of friends and family members. He struck out three and walked two.
Miami's Caleb Smith pitched 6 1/3 innings, allowing eight hits and three runs. He also had two hits at the plate.
McCutchen's two-run blast in the first was his seventh of the season.
The Marlins tied the game at 2 on base hits by Cameron Maybin and Lewis Brinson in the fourth.
The teams traded runs in the sixth. Austin Jackson gave the Giants a 3-2 lead before Bour tied it with a base hit.
The retractable roof was open for the 15th time this season, the most in a year since Marlins Park opened in 2012.
Giants: 1B Brandon Belt (appendix) is likely to have a couple rehab starts with the goal of joining the team on the next homestand beginning June 18 instead of playing this weekend in Los Angeles. ... RHP Johnny Cueto (left ankle) will have another bullpen session Friday. ... RHP Jeff Samardzija (right shoulder) will have a rehab start with Triple-A Sacramento on Friday with a pitch limit of 60-65 pitches.
Giants: RHP Dereck Rodriguez (1-1, 5.25 ERA) will start Thursday's series finale. Rodriguez, the son of former Marlins catcher and Hall of Famer Pudge Rodriguez, spent a lot of time around the Marlins when his father helped lead them to a World Series title in 2003.
Marlins: RHP Dan Straily (2-2, 4.08) is 4-0 with a 2.43 ERA in five career starts against the Giants.
More AP baseball: https://apnews.com/tag/MLBbaseball