![](/img/trans.png)
[英]Google iOS Cluster Manager "marker.userData" NIL after Cluster/de-Cluster
[英]How to access Google Maps marker data stored in marker.userData in Swift
我目前正在嘗試使用 marker.userData 屬性在 Google Maps markerInfoWindow 中動態顯示有關其特定位置的數據。
這是我的 function 設置 marker.userData 並將標記放在我的 map 實例上:
func putPlaces(places: [Place]) {
for place in places.prefix(10) {
print("*******NEW PLACE********")
let name = place.name
let address = place.address
let location = ("lat: \(place.geometry.location.latitude), lng: \(place.geometry.location.longitude)")
let locLat = place.geometry.location.latitude
let locLon = place.geometry.location.longitude
let place_id = place.place_id
let photo = place.photos
let types = place.types
let marker : GMSMarker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: locLat, longitude: locLon)
marker.icon = GMSMarker.markerImage(with: .black)
print("PLACE: \(place)")
print("PLACE.NAME: \(place.name)")
marker.userData = ["name" : "names"]
marker.map = self.mapView
}
}
我可以看到這里打印的具體地名^^^
這是我的 function(從 GoogleMapsAPI 文檔復制),我正在嘗試訪問 marker.userData 中的數據元素:
func mapView(_ mapView: GMSMapView, markerInfoContents marker: GMSMarker) -> UIView? {
print("Showing marker infowindow")
print("marker.userData: \(marker.userData)")
// error here!vvv
// print("marker.userData.name: \(marker.userData.name)")
// here I will pass this data to a swiftUI view that will display the data within marker.userData
let mInfoWindow = UIHostingController(rootView: MarkerInfoWindow())
mInfoWindow.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width - 48, height: 80)
return mInfoWindow.view
}
這是存儲在 marker.userData 中的數據(在打印 marker.userData 時從控制台獲取):
Optional(GMapProj.Place(geometry: GMapProj.Place.Location(location: GMapProj.Place.Location.LatLong(latitude: 42.3405476, longitude: -71.1465262)), name: "Boston Management Office", place_id: "ChIJpYqcF01444kRO8JeAqK2NuE", openingHours: Optional(GMapProj.Place.OpenNow(isOpen: false)), photos: nil, types: ["real_estate_agency", "point_of_interest", "establishment"], address: "113 Kilsyth Road # B, Brighton"))
在上面的最后一個 function 中,我嘗試打印出 marker.userData 中的“name”元素,但我一直收到錯誤消息,提示“Value of type 'Any?” 沒有成員“名稱”。 但是在將數據放入marker.userData之前,我可以在打印時訪問該名稱...
任何人都知道我如何訪問存儲在 marker.userData 中的數據並讀取它的元素?
marker.userData
類型是 Any?。 您不能在任何類型的 object 上使用點語法。 您需要將marker.userData
類型轉換為字典,然后訪問該值。 像這樣的東西。
let userData = marker.userData as? [String:String]
print("marker.userData.name": \(userData["name"])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.