如何在 google maps sdk 中使用函数外的变量

How to use a variable outside of a function in google maps sdk

我有以下结构

struct Talleres : Codable {
    let id : Int?
    let title : String?
}

我用来提取 json 的数据并在 google 地图(SDK)中添加标记。

使用变量 marker.accessibilityLabel = state.title 我保存标题以便在另一个函数中使用它。

func jsonMapTaller() {
.
.
.
    for state in self.marcadores {
        let coordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
        let marker = GMSMarker(position: coordinates)
        marker.map = self.map
        marker.icon = UIImage(named: "pin")
        marker.accessibilityLabel = state.title
    }
}

使用存储在 marker.accessibilityLabel 中的数据,我将此信息(标题)添加到以下函数中的自定义 InfoWindows:

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
.
.
.
    let myTitle:String! = marker.accessibilityLabel!
    infoWindow.titleLbl.text = myTitle
.
.
.
    infoWindow.center = mapView.projection.point(for: location)
    infoWindow.center.y = infoWindow.center.y - 107
    infoWindow.infoBtn.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    self.view.addSubview(infoWindow)
    return false
}

如何保存更多变量?例如,state.id 并且能够在函数 func mapView (_mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {...?

中使用它

要存储数据然后在另一个函数中使用它,请使用 userData

for state in self.marcadores {
        let coordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
        let marker = GMSMarker(position: coordinates)
        marker.map = self.map
        marker.icon = UIImage(named: "pin")
        marker.accessibilityLabel = state.title

       // store current marker data
        marker.userData = state
    }

然后您可以像这样在另一个函数中调用数据:(id 示例):

 myID = (marker.userData as! Talleres).id
 print(myID)