我目前正在尝试使用 marker.userData 属性在 Google Maps markerInfoWindow 中动态显示有关其特定位置的数据。
这是我设置 marker.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 文档中复制),我试图在其中访问 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 中的数据并读取它的元素?