Boni Machado
Boni Machado

Reputation: 197

How to declare GMSMapViewDelegate on SwiftUI

I'm trying to implement a solution with GoogleMapsApi with a map where user can touch the map and do things. For that, I understand delegate must be implemented, but I can't figure out how to achieve that with SwifUI. There's a lot of code samples on web, when in Swift, or even Objective C, but I couldn't find any on SwifUI.

Here's what I did (I'm trying to keep this code as simple as it could be):

struct GoogleMapsHomeView: UIViewRepresentable {

    func makeUIView(context: Self.Context) -> GMSMapView {
        
        let mapView = GMSMapView.map()
        
        return mapView
        
    }
    
    func updateUIView(_ mapView: GMSMapView, context: Context) {
        
    }
            
}

struct HomeView: View {
    
    var body: some View {
        GoogleMapsHomeView()
    }
    
}

struct HomeView_Previews: PreviewProvider {
    static var previews: some View {
        HomeView()
    }
}

How to declare GMSMapViewDelegate and related listener for a user map moving detection?

Upvotes: 1

Views: 1331

Answers (1)

Asperi
Asperi

Reputation: 257493

The common pattern is to use coordinator as delegate

struct GoogleMapsHomeView: UIViewRepresentable {

    func makeUIView(context: Self.Context) -> GMSMapView {

        let mapView = GMSMapView.map()
        mapView.delegate = context.coordinator
        return mapView

    }

    func makeCoordinator() -> Coordinator {
       Coordinator(owner: self)
    }

    func updateUIView(_ mapView: GMSMapView, context: Context) {
    }

    class Coordinator: NSObject, GMSMapViewDelegate {
       let owner: GoogleMapsHomeView       // access to owner view members,

       init(owner: GoogleMapsHomeView) {
         self.owner = owner
       } 

         // ... delegate methods here
    }
}

Upvotes: 4

Related Questions