Search code examples
iosswiftgoogle-mapsgoogle-maps-sdk-ios

Passing an object to custom view in Google maps SDK


I have custom view (a nib with its class) that I show when user taps on map marker. I also have an array of objects from where I'd like to show data of selected object when user taps on one of the markers. I create markers from the same array in a separate method. How to I get my element in array (to show additional data) when user taps the marker ? Or is there another way to get the object from array based on pressed marker. Apart from regexing based on lon and lat etc ?


Solution

  • I solved this by adding my model to

    marker.userData
    

    example:

    func addMarkers(){
    
        for place in places{
    
            let marker = GMSMarker()
            let placeLat = place.latitude
            let placeLon = place.longitude
            marker.position = CLLocationCoordinate2D(latitude: CLLocationDegrees(placeLat), longitude: CLLocationDegrees(placeLon))
            marker.appearAnimation = .pop
            marker.map = mpView
            marker.userData = place
    
        }
    
    }
    

    Then later I access it in:

    func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {

        let title = (marker.userData as! placeModel).name
        let add = (marker.userData as! placeModel).address
        let id = (marker.userData as! placeModel).id
        let image = (marker.userData as! placeModel).image
        let imageAddressInDocuments = ("\(getDocumentsDirectory())\(image)")
        print("image address in documents %@", imageAddressInDocuments )
        var infoWindow = Bundle.main.loadNibNamed("custView", owner: self, options: nil)?.first as! custView
        infoWindow.titleLabel.text = title
        infoWindow.addressLabel.text = add
        infoWindow.restaurantImage.image = image != "" ? UIImage(contentsOfFile: imageAddressInDocuments) : UIImage(named: "addImage")
    
    
        return infoWindow
    }