我目前正尝试使用markr.userData属性在谷歌地图markrInfoWindow中动态显示有关其特定位置的数据。
这是我的函数,用于设置markr.userData并在我的地图实例上放置标记:
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
}
}
我可以看到具体的地点。这里打印的名称^^^
这是我的功能(从GoogleMapsAPI文档复制而来(,我正在尝试访问markr.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
}
这是存储在markr.userData中的数据(打印markr.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"))
在上面的最后一个函数中,我试图打印出markr.userData中的"name"元素,但我一直收到一个错误,说"Value of type"Any?"没有成员"name"。但在我将数据放入标记之前,我可以在打印时访问名称。userData…
有人知道我如何访问存储在markr.userData中的数据并读取其元素吗??
marker.userData
类型为Any?。不能在任何类似类型的对象上使用点语法。您需要将marker.userData
类型转换为字典,然后访问该值。像这样的东西。
let userData = marker.userData as? [String:String]
print("marker.userData.name": (userData["name"])