我目前正在尝试使用marker.userData 属性在Google map markerInfoWindow 中动态显示有关其特定位置的数据。
这是我设置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
}
}
我可以看到这里打印的具体地点名称^^^
这是我的函数(从 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"))
在上面的最后一个函数中,我尝试打印出marker.userData中的“name”元素,但我不断收到错误消息“Value of type 'Any?'”没有成员“姓名”。但在将数据放入marker.userData 之前打印时我可以访问该名称...
有人知道我如何访问marker.userData中存储的数据并读取它的元素吗?
最佳答案
marker.userData
类型是 Any?。您不能在 Any 类型的对象上使用点语法。您需要将 marker.userData
类型转换为字典,然后访问该值。像这样的东西。
let userData = marker.userData as? [String:String]
print("marker.userData.name": \(userData["name"])
关于ios - 如何在 Swift 中访问存储在marker.userData中的Google map 标记数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58828778/