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?
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
}
}
mapView.selectedMarker = marker
. –
Latin Simple Way Swift 5
marker.icon = GMSMarker.markerImage(with: UIColor.green)
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.
If you use RxSwift, here is an elegant solution with RxGoogleMaps
Observable.combineLatest(mapView.rx.selectedMarker,
mapView.rx.selectedMarker.skip(1))
.subscribe(onNext: { (old, new) in
old?.icon = GMSMarker.markerImage(with: nil)
new?.icon = GMSMarker.markerImage(with: UIColor.red)
})
.disposed(by: disposeBag)
Observable.zip
instead of Observable.combineLatest
: github.com/RxSwiftCommunity/RxGoogleMaps/blob/master/Example/… –
Unreligious © 2022 - 2024 — McMap. All rights reserved.