如何在Swift中选中Google地图标记时更改其颜色?

11

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

4个回答

24

您可以使用GMSMarker.markerImage(with: <UIColor?>)来重置标记的图标。

文档:Google Maps iOS SDK GMSMarker Class 参考

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
如果您点击一个标记,然后点击地面,再点击另一个标记,那么就会选择两个标记。 - duan
正如@duan所建议的,您的解决方案存在问题。 - Nidhin
是的,当您手动设置所选标记时,@duan所描述的行为会发生。Google Maps API会自动为您设置所选标记,因此不需要使用此行“mapView.selectedMarker = marker”。 - Braden Holt

3

Swift 5 简易方法

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

2

原来的回答对我来说不起作用,因为如果用户在地图上点击非标记位置,则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事件。翻译成中文为:"这个方法的实现原理是,当用户点击非标记点时,信息窗口会关闭,从而触发didCloseInfoWindowOf事件。"

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

他们的文档中还有一个官方示例,使用 Observable.zip 而不是 Observable.combineLatest:https://github.com/RxSwiftCommunity/RxGoogleMaps/blob/master/Example/ViewController.swift - angtlin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接