Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 908
Derek Soike Avatar asked Dec 02 '16 18:12

Derek Soike


3 Answers

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
    }
}
like image 103
Derek Soike Avatar answered Nov 11 '22 01:11

Derek Soike


Simple Way Swift 5

marker.icon = GMSMarker.markerImage(with: UIColor.green)
like image 44
Shakeel Ahmed Avatar answered Nov 11 '22 02:11

Shakeel Ahmed


The accepted answer wasn't working for me because if a user tapped a non-marker on the map, selectedMarker would be set to nil. If the user then tapped another marker, triggering the didTap callback, the selectedMarker would be nil and thus retain its selected state/color.

The fix for me was to remove that selectedMarker logic from didTap and move it to didCloseWindowOf.

Here's the code:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    marker.icon = UIImage(named: "map_marker_selected")
    return false // return false to display info window
}

func mapView(_ mapView: GMSMapView, didCloseInfoWindowOf marker: GMSMarker) {
    marker.icon = UIImage(named: "map_marker_unselected")
}

This works because when the user taps a non-marker, the info window closes which triggers didCloseInfoWindowOf.

like image 2
Braden Holt Avatar answered Nov 11 '22 01:11

Braden Holt