我有一个GMSMapView
的视图控制器,并在地图上加载了许多标记。我可以使用mapView.selectedMarker = ...
更改选择的标记,但如何更改所选标记的颜色?
答案 0 :(得分:19)
您可以使用GMSMarker.markerImage(with: <UIColor?>)
重置标记的图标。
文档: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
}
}
答案 1 :(得分:0)
如果你使用RxSwift,这是一个优雅的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)
答案 2 :(得分:0)
Simple Way Swift 4
marker.icon = GMSMarker.markerImage(with: UIColor.green)
答案 3 :(得分:0)
接受的答案对我不起作用,因为如果用户在地图上点击了非标记,则selectedMarker将设置为nil。如果用户随后点击另一个标记,从而触发didTap回调,则selectedMarker将为nil,从而保留其选择的状态/颜色。
对我来说,解决方法是从didTap中删除该selectedMarker逻辑,然后将其移至didCloseWindowOf。
代码如下:
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")
}
之所以起作用,是因为当用户点击非标记时,信息窗口关闭,从而触发didCloseInfoWindowOf。