While trying out the Google Maps SDK on iOS and Google Maps Directions API I noticed that Google’s Getting Started code hasn’t been updated for Swift 3. Here are the changes required to get the code to work.
Google Maps SDK
- Follow first 3 steps (install latest xcode, install sdk, get api key) at https://developers.google.com/maps/documentation/ios-sdk/start.
- Create a single view application in Xcode. For viewDidLoad() function in ViewController.swift, add the following code. Note: I decided to include the API key under viewDidLoad() for simplicity.
GMSServices.provideAPIKey("YOUR_API_KEY") let camera = GMSCameraPosition.camera(withLatitude: -33.868, longitude:151.2086, zoom:6) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera:camera) let marker = GMSMarker() marker.position = camera.target marker.snippet = "Hello World" marker.appearAnimation = kGMSMarkerAnimationPop marker.map = mapView self.view = mapView
- Run the app. You should see a map with a single marker centered over Sydney, Australia. If you click on the marker, you should see the text “Hello World” above it. If you see the marker, but the map is not visible, confirm that you have provided your API key.
Google Maps Directions API
I decided to use Alamofire iOS library to make HTTP requests to the Google Maps Directions API as it makes it much easier than the built-in Swift methods.
- Use Alamofire installation instructions here: https://github.com/Alamofire/Alamofire. I went with the CocoaPods method as it was what Google Maps SDK used and it worked well for me.
- Get an API key for Google Maps Directions API here: https://developers.google.com/maps/documentation/directions/ (about halfway down the page).
- Create a single view application in Xcode. For viewDidLoad() function in ViewController.swift, add the following code.
Alamofire.request("https://maps.googleapis.com/maps/api/directions/json?" + "origin=Disneyland&destination=Universal+Studios+Hollywood4&" + "key=YOUR_API_KEY").responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: (JSON)") } }
- Run the app. You should see the waypoints and directions in the Xcode Console.