在 swift 中选择时如何更改 google 地图标记颜色?

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

我有一个带有 GMSMapView 的视图控制器,并在地图上加载了一些标记。我可以使用 mapView.selectedMarker = ... 更改选择的标记,但如何更改所选标记的颜色?

您可以使用 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
    }
}

如果你使用 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)

简单方法Swift 5

marker.icon = GMSMarker.markerImage(with: UIColor.green)

已接受的答案对我不起作用,因为如果用户点击地图上的 non-marker,selectedMarker 将设置为 nil。如果用户随后点击另一个标记,触发 didTap 回调,则 selectedMarker 将为 nil 并因此保留其选择的 state/color.

我的解决方法是从 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")
}

这是有效的,因为当用户点击 non-marker 时,信息 window 关闭,触发 didCloseInfoWindowOf。