Friday 29 July 2016

Integrate google map in an iOS app

In iOS development we have situation where we need to add  a map in our app. Google provides the iOS SDK to integrate map in an iOS app.

We can add SDK  either manually or using COCOAPODS. Here we are adding through pod .

Before adding google map SDK make sure we have COCOAPOD install in out system. If we have po d in our system  then follow these steps  to make a pod file :

1) Go to project directory and run the command
     
                pod init

This will make a pod file in your project directory.

2) Now open the Podfile

            nano Podfile

Add the following lines to add google map in our project:

    source 'https://github.com/CocoaPods/Specs.git'

target 'Indi Beats' do
pod 'GoogleMaps'
  pod 'GooglePlaces'
end

Now save and exit the pod file and run the pod install command to add the google map. This will make a file with an extension of  .xcworkspace . Now open this file to open the project in xocode .

Now go to developer site of google and follow these steps to enable the Google maps SDK for iOS on the  Google API console .

1) Go to Google API Console .

2) Creare or select a project .

3) Click Continue to enable the Google Maps SDK for iOS.

4) On the Credentials page, get an iOS key and enter your app's bundle identifier when prompted .

5) Click Create .

This will create  an API key for Google Maps .

Add API key in iOS application:

Add API key  in your AppDelegate.m file

1) Add the import statement:
      
      @import GoogleMaps;

2) In application:didFinishWithLaunchingOptions: method, add the following line:

      [GMSServices provideAPIKey:@"your api key"];


Add a map :

In your view controller add the following  import statement:

#import <GoogleMaps/GoogleMaps.h> 

-(void)addMap{

//1  Create camera position
      GMSCameraPosition *cameraPos =  [GMSCameraPosition cameraWithLatitude:-33.86 longitude:151.20 zoom:10];

//2 Create map view
     GMSMapView *mapView = [GMSMapView  mapWithFrame:CGRectZero camera:cameraPos];

     self.view = mapView ;

//3 We can also create a marker

     GMSMarker *marker =  [GMSMarker alloc]init];
    
     //set position of the marker
      marker.position = CLLocationCoordinate2DMake(-33.86,151.20);
      
      marker.map =  mapView ;
}

That's it. This is how we add a map in an iOS app,