How to change google maps marker color when selected in swift?

Derek Soike picture Derek Soike · Dec 2, 2016 · Viewed 15.9k times · Source

I have a view controller with a GMSMapView and have loaded a number of markers onto the map. I can change which marker is selected with mapView.selectedMarker = ... but how do I change the color of the selected marker?

Answer

Derek Soike picture Derek Soike · Dec 2, 2016

You can use GMSMarker.markerImage(with: <UIColor?>) to reset a marker's icon.

Docs: Google Maps iOS SDK GMSMarker Class Reference

import GoogleMaps

// view controller
class MapViewController: UIViewController {

    // outlets
    @IBOutlet weak var mapView: GMSMapView!

    // view did load method
    override func viewDidLoad() {
        super.viewDidLoad()

        // set map view delegate
        mapView.delegate = self
    }
}

// extension for GMSMapViewDelegate
extension MapViewController: GMSMapViewDelegate {

    // tap map marker
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
        print("didTap marker \(marker.title)")

        // remove color from currently selected marker
        if let selectedMarker = mapView.selectedMarker {
            selectedMarker.icon = GMSMarker.markerImage(with: nil)
        }

        // select new marker and make green
        mapView.selectedMarker = marker
        marker.icon = GMSMarker.markerImage(with: UIColor.green)

        // tap event handled by delegate
        return true
    }
}