如何访问Swift中存储在marker.userData中的Google Maps标记数据

问题描述 投票:0回答:1

我目前正在尝试使用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'元素,但我不断收到错误消息,提示'Type of'Any?没有成员“名称”。但是在将数据放入marker.userData ...]之前,我可以在打印时访问名称。

任何人都知道我如何访问存储在marker.userData中的数据并读取其元素?

我目前正在尝试使用marker.userData属性在Google Maps markerInfoWindow中动态显示有关特定位置的数据。这是我设置marker.userData和...

ios swift google-maps marker gmsplace
1个回答
0
投票

marker.userData类型是任何?。不能在任何类型的对象上使用点语法。您需要将marker.userData类型转换为字典,然后访问该值。像这样。

© www.soinside.com 2019 - 2024. All rights reserved.