Swift检测在谷歌地图上按下了哪个标记

时间:2017-03-16 17:10:47

标签: ios swift xcode google-maps

我想知道如何检测地图上按下了哪个标记。我在地图上有很少的标记,从API下载的标记数组中有Marker类,它包含一些数据。现在我想知道在按下标记后如何将数据发送到下一个VC。将整个Array发送到下一个VC,然后以某种方式通过另一个VC上的数组获取数据是不是很好?

1 个答案:

答案 0 :(得分:4)

您可以使用userData属性存储所需的唯一数据。

for (index,i) in markers.enumerated() {
      let marker = GMSMarker()
      marker.position = CLLocationCoordinate2DMake(i.lat, i.lng)
      marker.userData = ["index": index]
      print("@@@\(i.id)")
      marker.title = i.name
      marker.map = mapView            
}

在didTap方法中执行这样的操作。

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {

    performSegue(withIdentifier: "details", sender: marker)
    return true
}

现在在prepareForSegue中获取userData的对象索引。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "details" {
        var nextVC =  segue.destination as! VC2
        if let marker = sender as? GMSMarker,
           let dict = marker.userData as? [String:Int] {


             print(dict["index"])
            // use this array index to access object from array
        } 
    }
}
相关问题