【问题标题】:How to use a variable outside of a function in google maps sdk如何在谷歌地图sdk中的函数之外使用变量
【发布时间】:2018-10-16 20:34:01
【问题描述】:

我有以下结构

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

我用来提取 json 的数据并在谷歌地图 (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 {...中使用?

【问题讨论】:

    标签: swift google-maps google-maps-markers


    【解决方案1】:

    要存储数据然后在另一个函数中使用它,请使用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)
    

    【讨论】:

      猜你喜欢
      • 2022-11-15
      • 1970-01-01
      • 2023-04-04
      • 2021-06-26
      • 1970-01-01
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多