Search code examples
iosswiftxcodeswiftuigoogle-maps-sdk-ios

How to style Google Maps in SwiftUI with JSON


I am new to XCode 11 and SwiftUI and have been following a tutorial (famous last words): https://developers.google.com/maps/documentation/ios-sdk/styling, trying to create a custom Google Maps interface using the Google Maps SDK. I have a basic map view in my app already, but I am trying to use a JSON file to style the map (specifically, I am trying to highlight local roads). My problem is that the solution provided by the Google documentation is not for SwiftUI, as it uses a ViewController. How should I use a JSON file to style the maps in SwiftUI? As I said I am a total newbie to Swift, so I would greatly appreciate answers on a beginner level, if possible. My code for the Map View called in ContentView.swift looks like this (not sure if it's relevant):

import SwiftUI

import GoogleMaps



struct GoogleMapsView: UIViewRepresentable {

    private let zoom: Float = 15.0



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

        let camera = GMSCameraPosition.camera(withLatitude: 33.3969, longitude: -84.5963, zoom: 13.0)

        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)

        return mapView

    }

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



    }

}

struct GoogleMapsView_Previews: PreviewProvider {

    static var previews: some View {

        GoogleMapsView()

    }

}

Solution

  • I think it doesn't matter if you're using SwiftUI or not. The important part is:

    if let styleURL = Bundle.main.url(forResource: "style", withExtension: "json") {
       mapView.mapStyle = try GMSMapStyle(contentsOfFileURL: styleURL)
    

    just add it between this:

    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    ->
    return mapView