在 Google 地图 SDK 中将对象传递到自定义视图

Passing an object to custom view in Google maps SDK

我有自定义视图(带有 class 的笔尖),当用户点击地图标记时会显示该视图。我还有一组对象,当用户点击其中一个标记时,我想从中显示所选对象的数据。我用单独的方法从同一个数组创建标记。当用户点击标记时,如何让我的元素进入数组(以显示附加数据)?或者是否有另一种方法可以根据按下的标记从数组中获取对象。除了基于 lon 和 lat 等的正则表达式之外?

GMSMapViewDelegate has the delegate function which lets you to return your customView as info window.

optional public func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView?

您必须子类化 GSMarker,它在 init 中采用您的模型。

class MapItem:GMSMarker {
    var model: Model!  //your data model
    init(data: Model) {
        super.init()
        // pass cordinate
        self.position = CLLocationCoordinate2D(latitude: data.latitude!, longitude: data.longitude!) 
        // pass Model
        self.model = data 
    }
}

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    // Wrap GSMarker to your custom marker which is MapItem here
    let customMarker = marker as! MapItem 
      // pass your model to CustomView(marker info window) in init 
    let customView = CustomView(markerModel: customMarker.model)
    return customView
}

我通过将我的模型添加到

解决了这个问题
marker.userData

示例:

func addMarkers(){

    for place in places{

        let marker = GMSMarker()
        let placeLat = place.latitude
        let placeLon = place.longitude
        marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(placeLat), longitude: CLLocationDegrees(placeLon))
        marker.appearAnimation = .pop
        marker.map = mpView
        marker.userData = place

    }

}

然后我在以下位置访问它:

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {

    let title = (marker.userData as! placeModel).name
    let add = (marker.userData as! placeModel).address
    let id = (marker.userData as! placeModel).id
    let image = (marker.userData as! placeModel).image
    let imageAddressInDocuments = ("\(getDocumentsDirectory())\(image)")
    print("image address in documents %@", imageAddressInDocuments )
    var infoWindow = Bundle.main.loadNibNamed("custView", owner: self, options: nil)?.first as! custView
    infoWindow.titleLabel.text = title
    infoWindow.addressLabel.text = add
    infoWindow.restaurantImage.image = image != "" ? UIImage(contentsOfFile: imageAddressInDocuments) : UIImage(named: "addImage")


    return infoWindow
}