Search code examples
iosarraysswiftparameter-passingmarker

How to pass specific element from array to another view or function? Swift


I'm loading data from server and passing it to an array. This data includes coordinates, text, images etc. Also it contains variable, named "id" (I thought about sorting array for specific id, but not sure if this is a good solution). This data is used to show markers on map. My task is to show this marker's details on separate view. How to tell this details screen which marker was chosen or how to get specific element from array based on chosen marker?

This is were I create markers:

for element in spots {
        let image = UIImage(named: element.type)

        let position = CLLocationCoordinate2D(latitude: element.coordinates.latitude, longitude:
            element.coordinates.longitude)
        marker = GMSMarker(position: position)
        marker.icon = image
        marker.map = mapView
    }

Solution

  • You can use GMS delegate method to check which marker is tapped.

    for element in spots {
        let image = UIImage(named: element.type)
    
        let position = CLLocationCoordinate2D(latitude: element.coordinates.latitude, longitude:
            element.coordinates.longitude)
        marker = GMSMarker(position: position)
        marker.icon = image
        marker.map = mapView
        // add the element info to marker userData property 
        marker.userData = element
    }
    
    
    // function to check if which icon tapped
    
    func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool {
    
        // get the element info from marker
        let element = marker.userData
        //code to navigate to detail view
    }
    

    Hope this will help!