+1

Google Maps SDK

Working with maps in iOS consists of an entire programming chapter, as there are tons of things that a developer can do with them. From just presenting a location on a map to drawing a journey’s route with intermediate positions, or even exploiting a map’s possibilities in a completely different way, dealing with all these undoubtably is a great experience that leads to amazing results.

Google Maps SDK for iOS allows us to add maps to our iOS applications. Google Maps SDK automatically handles the Google Maps, and also response to the user’s activities such as

  •   Tap
    
  •   movement
    
  •   zoom, etc.
    

Google Maps SDK also allows us to get user’s current location. We can get the location on the map by latitude and longitude of the place.

Objective

My objective in this post would be to explain how you can add Google Maps SDK to implement features like show specific location, show route from one place to another, show user’s current location, show user’s updated location, etc. First of all, you need API Key for Google Maps. For that you need a Google Account.

Get API Key

To use the Google Maps SDK, we need an API key. API key is a key through which we can make calls to Google API from an iOS Application. Follow these steps to get API Key.

  1. Sign into Developers Console https://console.developers.google.com/iam-admin/projects using your Google Account.
  2. Create Project if you haven’t created it yet, else go to Step 3.
    • Add name of the project.
    • Click on Create button.
  3. Select the project by clicking on Select a project button available on Top-Right Corner.
  4. Click on Enable and Manage APIs.
  5. It will list all the Google APIs. Select Google Maps SDK for iOS listed in Google Maps API.
  6. It will prompt to Enable the API. Click on Enable API.
  7. Your Google Maps SDK now enabled. But you can’t use it before creating credentials. Click on Go to Credentials to create credentials
  8. Click on New Credentials. A drop-down box appears by clicking on New Credentials. Click on API Key.
  9. Click on iOS Key.
  10. It will ask the name of the iOS API Key and Bundle Identifier of the iOS Application.
    • Add name of the iOS API Key
    • Add Bundle Identifiers of the iOS Applications. You can add multiple Bundle Identifiers in this section. It will accept request from iOS Applications with any of the Bundle Identifiers listed here.
    • When you are ready with all configurations, click on Create button.
  11. It will create API Key and display on the screen. Copy this API Key and store it. You will need this API Key to use Google Maps SDK in your iOS Application

Project Configuration

Now create a new Xcode project. To integrate Google Maps SDK for iOS, you need to get GoogleMap framework. Drag GoogleMaps.framework to the project in Xcode. Now you can find GoogleMaps.framework framework in your project.

  • Right-click on it and select Show in finder
  • Double click on GoogleMaps.framework in finder and select Resources folder.
  • You can find GoogleMaps.bundle.
  • Drag GoogleMaps.bundle to the Xcode project.

Add Other Frameworks

Google Maps SDK needs several other frameworks. Such as

  • Accelerate.framework
  • AVFoundation.framework
  • CoreBluetooth.framework
  • CoreData.framework
  • CoreGraphics.framework
  • CoreLocation.framework
  • CoreText.framework
  • GLKit.framework
  • ImageIO.framework
  • libc++.dylib
  • libicucore.dylib
  • libz.dylib
  • OpenGLES.framework
  • QuartzCore.framework
  • Security.framework
  • SystemConfiguration.framework

Add Bridging Header

As GoogleMaps.framework is available in Objective C, we need to add bridging header to our Swift project. By using bridging header, we can use Objective C code in our Swift application.

Display Map in our iOS Application

Open the AppDelegate.swift file and use following lines of code in the application (_didFinishLaunchingWithOptions:) method.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    GMSServices.provideAPIKey("<YOUR_API_KEY_HERE>")
    return true
}

You have to set your iOS application API Key in <YOUR_API_KEY_HERE>.

Now in GoogleMapViewController.swift, add the following lines of code in viewDidLoad() method.

override func viewDidLoad() {
    let camera: GMSCameraPosition = GMSCameraPosition.cameraWithLatitude(22.300000, longitude: 70.783300, zoom: 10.0)
    vwGMap = GMSMapView.mapWithFrame(self.view.frame, camera: camera)
    vwGMap.camera = camera
}

This method initializes the GMSCameraPosition. By default initial location will be displayed once map is loaded. For that you should get the latitude and longitude of the place.

Get User’s Current Location

  • Add your class to subclass of CLLocationManagerDelegate.
  • Create variables of class CLLocationManager and GMSMapView.
    var locationManager = CLLocationManager()
    var vwGMap = GMSMapView()
  • Add following lines of code in viewDidLoad() method of your ViewController.
override func viewDidLoad() {
    super.viewDidLoad()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyKilometer

    // A minimum distance a device must move before update event generated
    locationManager.distanceFilter = 500

    // Request permission to use location service
    locationManager.requestWhenInUseAuthorization()

    // Request permission to use location service when the app is run
    locationManager.requestAlwaysAuthorization()

    // Start the update of user's location
    locationManager.startUpdatingLocation()
        
    // Add GMSMapView to current view
    self.view = vwGMap
}

CLLocationManagerDelegate methods

When we request the permission by locationManager.requestWhenInUseAuthorization(), it will call locationManager(_didChangeAuthorizationStatus:). In which I have enabled myLocationEnabled to true. Now I am able to get the user’s current location.

func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    if (status == CLAuthorizationStatus.AuthorizedWhenInUse) {
        vwGMap.myLocationEnabled = true
    }
}

Now locationManager(_didUpdateLocations) method is called at specific interval.

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let newLocation = locations.last
    vwGMap.camera = GMSCameraPosition.cameraWithTarget(newLocation!.coordinate, zoom: 15.0)
    vwGMap.settings.myLocationButton = true
    self.view = self.vwGMap
}

In this method, we can get the updated locations. I have set the camera with the target location.

Create marker and set the location

We can also set marker at the user’s current location. For that you need a variable of GMSMarker variable.

    let marker = GMSMarker()

I would be using following lines of code to set the marker at the specified location.

    // Create marker and set location
        marker.position = CLLocationCoordinate2DMake(newLocation!.coordinate.latitude, newLocation!.coordinate.longitude)
    marker.map = self.vwGMap

Add this code to locationManager(_didUpdateLocations) method. Now user will get the marker at his/her current location.

OutPut

info.png

Conclusion

I hope you will find this post helpful while working with Google Maps SDK in iOS Swift. For referance https://developers.google.com/maps/documentation/ios-sdk/start or https://developers.google.com/maps/documentation/ios-sdk/intro and project link https://github.com/dina28/GoogleMapDemo


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí