Search code examples
xcodegoogle-mapsswiftuixcode11

Google Maps integration into SwiftUI


Im fairly new into programming with Xcode and SwiftUI and am having trouble integrating Google Maps into a SwiftUI project.

I added all the right API keys into my AppDelegate.swift file and have created a view called GoogMapView that i am trying to use to display an instance of Google maps. This is my code in the file GoogMapView:

import SwiftUI
import MapKit
import UIKit
import GoogleMaps
import GooglePlaces

struct GoogMapView : UIViewRepresentable {
    func makeUIView(context: Context) -> GMSMapView {
        GMSMapView(frame: .zero)
    }

    func updateUIView(_ view: GMSMapView, context: Context) {
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        view = mapView

        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView
    }

I keep getting an error at 'view = mapView' but everything i tried has failed. Any idea how to set this up so i can call it in a main view?


Solution

  • I am also a new iOS developer. I was looking into the same thing and stumbled on your question. Since I am new to iOS, I can't claim it follows all the proper conventions, but this code works to display the map on the simulator with SwiftUI at a basic level. Solution is based on your code, and Matteo's observation.

    import SwiftUI
    import UIKit
    import GoogleMaps
    
    struct ContentView: UIViewRepresentable {
        let marker : GMSMarker = GMSMarker()
    
        /// Creates a `UIView` instance to be presented.
        func makeUIView(context: Self.Context) -> GMSMapView {
            // Create a GMSCameraPosition that tells the map to display the
            // coordinate -33.86,151.20 at zoom level 6.
            let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
            let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    
            return mapView
        }
    
        /// Updates the presented `UIView` (and coordinator) to the latest
        /// configuration.
        func updateUIView(_ mapView: GMSMapView, context: Self.Context) {
            // Creates a marker in the center of the map.
            marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
            marker.title = "Sydney"
            marker.snippet = "Australia"
            marker.map = mapView
        }
    
    }