Tag Archives: IPhone

blog_image400x545

PhoneGap Cordova Accelerometer HTML5 Canvas Animation XCode Example


This is a template example using the accelerometer with Cordova or Phonegap and animating a sprite on the HTML5 canvas.blog_image400x545

Learn cocos2D Game Development
PhoneGap Essentials: Building Cross-Platform Mobile Apps

I was working on a game using the html canvas and the accelerometer. I developed a way to combine both in IOS using Objective C and the UIWebView in the UIKit. That approach limits distribution to the IOS platform but allows you to have all of the native UI items like screen navigation and just use the canvas for animations.

Then I became curious about distributing on multiple devices containing an accelerometer since the animation is being done in html canvas. The solution was a hybrid mobile platform like Cordova. UI in Cordova is really up to you although you can find UI libraries written in HTML, JavaScript and JQuery optimized for mobile.

Here are screen shots for the app.

There is only one screen and these are just showing the animated red circle in different positions. The functionality is simple in that the red circle moves in the direction of the accelerometer’s x and y values – well with some adjustments but we will cover them in a bit.

When it reaches the boundaries of the canvas for either direction, it stop moving in that one direction. Thus you can move it to any corner and it will stay fixed and you can move it around the edges of the canvas.

You can also tap the canvas to start and stop the animation.

The Project Files

The project uses Cordova 1.6, XCode 4.3.2 and was tested using iOS 5.1 on a IPhone 4.

I had started the example using Cordova 1.5. Cordova 1.6 was released before completing this article and Cordova 1.6 changed the accelerometer values. The release notes included “Rewrite of accelerometer code and removed DeviceInfo old init approach” and “Added unification of accelerometer values on ios (based on android values)”. Boiling those entries down we get that the values are the same across platform, but if you are using IOS you better divide by 10. I commented in the code in case you are still using 1.5 or earlier.

I added a simple html console area to display debugging messages from the Javascript.

I also stripped out most of the extra Cordova comments that were not relevant to this example.

Download XCode Project Files

Step 1 – Install Cordova for XCode

Instructions for setting up your development environment are located at the PhoneGap site Getting Started with iOS.

Step 2 – Create New Cordova-based Application

Step 3 – Set XCode Project Options


Set the XCode project options as follows:

  • Product name: Here I used CordovaAccelerometerCanvas as the project name. You can use a name of your own choosing.
  • Company identifier: Provide your own reverse domain name.
  • Use Automatic Reference Counting: Uncheck

Step 4 – Choose A File Location

Once you select a file location on your computer you will have a folder structure as follows:

And in XCode you will see a project window as follows:

You may notice the project has a warning. Ignore this for now.

Step 5 – Create and Add the www Folder and Files to the Project

These are the normal setup instructions for a Cordova alias PhoneGap XCode project. You can skip this step if you are used to creating Cordova XCode projects.

The process is creating a www folder by running the app once in the IPhone simulator and then add to the project explorer.

First run the app in the IPhone simulator.

The app runs but complains of the missing index.html file.

A www folder with this file and one other js file were created on your file system as this the app launched in the simulator. Here you see them and you need to drag the www folder into the Project Explorer. Do not drag to or copy to the XCode folders outside of XCode.

Fill out the “Choose options for adding these files” dialog as follows.

  • Destination: Unchecked
  • Folders: “Created folder references for added folders” selected.
  • Add to targets: CordovaAccelerometerCanvas checked.

And here are the final results you see in the Project Explorer window.

Run the app in the IPhone simulator one more time.

This time you will be greeted with an Alert dialog with the “Cordova is working” message.

Step 7a – The Completed index.html File

Here is the full index.html file completed for your copy convenience. Just replace your index.html file with this and you can test on your device.

I removed Cordova code comments and commented code not related to our needs that is included in the index.html file.



    
        
        
        
        
        
    
    
        

Accelerometer + HTML5 Canvas

This text is displayed if your browser does not support HTML5 Canvas.

The remaining part of this article will explain the parts of the index.html file by topic.

Step 7a – The index.html body Section

Key in this section is the canvas tag on line 189. I am using the ontouchend event versus the onclick event to prevent a canvas flicker when the screen is touched. The action is to start and stop the animation.

Line 193 is my own html debugging console for simple examples. You should see the accelerometer values displayed in here when testing on a device.

 
        

Accelerometer + HTML5 Canvas

This text is displayed if your browser does not support HTML5 Canvas.


Step 7b – The index.html Accelerometer Code

Cordova provides an api for the accelerometer. We use a good portion of it with this example.

The variables on lines 11 to 14 are helpers for the animation. We do not need them for raw access to the accelerometer. You can see their explanations and we will look at them applied further along.

            var SPEED = 10;                 // Canvas redraw speed in milliseconds and accelerometer frequency
            var DISTANCE_FACTOR = .1;       // Factor to adjust accelerometer values to screen distance. Cordova 1.6 changed to values to be Android compatible which appeared to be * 10. For Cordova 1.5 make this value 1.
            var ax = 0;                     // Acceleration x axis (Accelerometer value adjusted for direction)
            var ay = 0;                     // Acceleration y axis (Accelerometer value adjusted for direction)

Line 24 has an id for the accelerometer watch event. This can be used to clear the watch event when you do not need the accelerometer anymore.

            var watchID;                    // Accelerometer.watchAcceleration return value. 

I created the startWatch function for this example to call when we need to start collecting accelerometer data.

The accelerometer works by calling your own event handler functions using the watchAcceleration method you see on line 54.
The watchAcceleration take a reference to your success and error handler as the first two arguments.

It also takes an options object for the third argument. Currently the only option object key is frequency measured in milliseconds. I am using the SPEED variable set to 10 milliseconds for the frequency.

The watchAcceleration returns an id so we can refer to it later.

            /* Start watching the accelerometer */
            function startWatch() 
            {
                var options = { frequency: SPEED };
                watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options);
            }   

The stopWatch function is also created for the example to stop requesting accelerometer data anywhere in the code. Line 60 uses the clearWatch method to stop watching the accelerometer. The watchID variable from line 54 identifies the watch activity to end.

To prevent throwing errors, logic is included to test for the watchID.

            // Stop watching the accelerometer
            function stopWatch() 
            {
                if (watchID) {
                    navigator.accelerometer.clearWatch(watchID);
                    watchID = null;
                }
            }

The onSuccess function on line 64 is called from the watchAcceleration on line 54.

The onSuccess function passes an acceleration object. The acceleration object currently has four values and they are all displayed in our html console on line 71.

The other code in the onSuccess method prepares variables for the animation.

The ax and ay variables on line 68 and 69 are accelerometer x and y values respectively. They represent acceleration in our animation.

For the x-axis value we need to reverse the value sign so the tilt of the device represents the direction of the x-axis animation. Interesting this is for Cordova 1.6. In Cordova 1.5 this is not needed.

For the y-axis value we need to reverse the value sign if you are using Cordova 1.5. Again to represent the direction by the tilt of the device.

Finally the x and y acceleration values were adjusted with Cordova 1.6. As I had mentioned I started the example in Cordova 1.5 and was able to use the raw values. But with Cordova 1.6 the values are 10x so I added the DISTANCE_FACTOR variable set to .1 to compensate. Perhaps I should have called it a “VERSION_FACTOR”.

I had no need for z and timestamp properties in this example, but they are displayed for interest. You may get updates from the device due to your frequency of request, but the device has not sensed new values, so you can use the timestamp property in case you are using the accelerometer updates for a cpu intensive function that without a change is unnecessary.

            /* Accelerometer data callback */
            function onSuccess( acceleration )
            {
                // Set drawing acceleration values
                ax = acceleration.x * DISTANCE_FACTOR * -1; // -1 to change direction for Cordova 1.6. Removed for Cordova 1.5.
                ay = acceleration.y * DISTANCE_FACTOR ;// Add * -1 for Cordova 1.5;
                // Optional ouput for understanding accelerator values.
                console_log.innerHTML = 
                'Acceleration X: ' + acceleration.x + '
' + 'Acceleration Y: ' + acceleration.y + '
' + 'Acceleration Z: ' + acceleration.z + '
' + 'Timestamp: ' + acceleration.timestamp ; }

This final code snippet is simply the error handler for watching the accelerometer. Apparently there is no information provided for the error, so you will need to improvise.


            /*  Accelerometer error callback */
            function onError()
            {
                alert("Accelerometer Error");
            }

Step 7c – User Start and Stop Interaction

Touching the canvas starts and stops the animation. This starts on line 189 with the canvas tag ontouchend event calling the canvasTouchEnd() function on line 172.

           
                This text is displayed if your browser 
                does not support HTML5 Canvas.
            

There is the playing variable set on line 26 that retains the state of animation playing.

            var playing = true;             // Boolean if animation is playing.

The canvasTouchEnd function uses the playing boolean variable to determine starting or stopping animation and calls function to handle changing the animation playing state.

            /* Canvas tag touch end event handler */
            function canvasTouchEnd()
            {
                if (playing)
                {
                    stopPlay();
                }
                else
                {
                    startPlay();
                }
            }

The startPlay function first sets the playing state to true.

To start playing the velocity variables are set to zero. This prevents any timing issues that may cause the animation move in a direction not indicative of the tilt of the device when the animation is restarted.

Receiving events from the accelerometer is started with the call to the startWatch function we reviewed earlier.

Handing the canvas redraw is done on line 89 with a JavaScript timer. The timing of the of the canvas redraw is the same as the updates from the accelerometer. You could consider a different design where the accelerometer updates perform the canvas redraw. However the approach we are using allows animations to occur that not dependent on the accelerometer changes should you need to add them.

            /* Steps to start animation play */
            function startPlay()
            {
                playing = true;
                vx = 0;
                vy = 0;
                startWatch();
                drawID = setInterval(draw, SPEED);
            }

Stopping animation is done by clearing the timer interval, stopping the accelerometer watching and setting the playing state to false.

            /* Steps to stop animation play */
            function stopPlay()
            {
                clearInterval(drawID);
                stopWatch();
                playing = false;
            }

Step 7d – The index.html Canvas Animation

The canvas animation does not require Cordova. It is just an interesting way to demonstrate using the accelerometer. All the animation in the canvas could be done in any HTML5 web browser.

First is the canvas tag which has a predefined width and height. We could create the canvas tag dynamically in JavaScript, but I left it out to keep code simpler.

           
                This text is displayed if your browser 
                does not support HTML5 Canvas.
            

Next there are some variables that impact the canvas animation work.

Line 10 has a variable to reference the canvas 2d context to allow drawing. This will refer back to the canvas tag.

The SPEED variable on line 11 is for the JavaScript timer that will call the draw function. The draw function does all the work on the canvas.

Line 13 and 14 are acceleration values that are updated using the accelerometer.

The x and y on lines 14 and 15 are the position of the circle sprite we are animating.

The velocity variables are initialized to zero on lines 16 and 17.

Height and width of the canvas are repeated here for computing the boundaries for our animated circle sprite.

The diameter of the circle sprite is configurable on line 21

Adding some color on lines 22 and 23 for the circle sprite and background respectively.

Then we have on line 25 the JavaScript timer interval id for redrawing the canvas.

            var console_log;                // Debugging div on device
            var canvas_ctx;                 // HTML canvas 2d context
            var SPEED = 10;                 // Canvas redraw speed in milliseconds and accelerometer frequency
            var DISTANCE_FACTOR = .1;       // Factor to adjust accelerometer values to screen distance. Cordova 1.6 changed to values to be Android compatible which appeared to be * 10. For Cordova 1.5 make this value 1.
            var ax = 0;                     // Acceleration x axis (Accelerometer value adjusted for direction)
            var ay = 0;                     // Acceleration y axis (Accelerometer value adjusted for direction)
            var x;                          // Circle x position
            var y;                          // Circle y position
            var vx = 0;                     // Velocity x axis
            var vy = 0;                     // Velocity y axis
            var WIDTH = 320;                // Width of canvas
            var HEIGHT = 300;               // Height of canvas
            var RADIUS = 50;                // Width of circle object
            var CIRCLE_COLOR = "#f00";      // Circle color
            var CANVAS_COLOR = "#FAF7F8";   // Color of canvas background
            var watchID;                    // Accelerometer.watchAcceleration return value. 
            var drawID;                     // Draw time interval. 
            var playing = true;             // Boolean if animation is playing.

The init() function is called when the app boots up and here you see on line 43 and 44 the standard way to get the drawing context to the canvas tag.

Also the starting position of the circle sprite is placed at the center of the screen.

            /* Initialize canvas and animation */
            function init() 
            {
                var canvas = document.getElementById("canvas");
                canvas_ctx = canvas.getContext("2d");
                // Center 
                x = WIDTH / 2 ;
                y = HEIGHT/ 2 ;
                startPlay();
            }

There are some utility functions for drawing shapes in the html canvas. First we have the circle method which demonstrates how to draw a circle given x, y and radius values.

Discussing the values for drawing on the canvas are beyond the scope of this article but I strongly suggest you get a copy of Foundation HTML5 Animation with JavaScript.

The values for the canvas 2d context arc method are centerX, centerY, radius, startingAngle in radians, endingAngle in radians and the boolean antiClockwise.

The startingAngle and endingAngle have radian values to draw a complete circle.

Note you will need to compensate for x and y because the values for x and y reference the center. You will see this offset in the boundary testing code.

            /* Draw circle */   
            function circle( x, y, r ) 
            {
                canvas_ctx.beginPath();
                canvas_ctx.arc(x, y, r, 0, Math.PI*2, true);
                canvas_ctx.fill();
            }

Next is the rect function on line 106 to draw a rectangle. The canvas 2d context rect method is straightforward drawing from top left corner of the rectangle.

            /* Draw rectangle */
            function rect( x, y, w, h ) 
            {
                canvas_ctx.beginPath();
                canvas_ctx.rect(x,y,w,h);
                canvas_ctx.closePath();
                canvas_ctx.fill();
            }

In drawing for animation, you will need to clear the canvas, so this clear function allows that to happen. The one line is clearRect method of the canvas 2d context. The clearRect method clears a rectangular area and here we have the entire canvas covered.


            /* Clear canvas */
            function clear() 
            {
                canvas_ctx.clearRect(0, 0, WIDTH, HEIGHT);
            }

The drawing position computations and actual drawing are both done in the draw function. Some animation applications you may want to split the drawing from the computations, but in this case putting them together meets our needs.

The velocity in the x and y directions are computed on lines 122 and 123. Simply they are increased or decreased by the change in acceleration values from the accelerometer. Acceleration values contain direction as well as acceleration.

Then we recompute the circle sprite position on lines 125 and 126.

Lines 127 – 151 are computing the boundaries for the canvas in relation to the proposed position of the center point, the x and y values, of the circle sprite. If any boundary is reached, then the velocity for that direction is set to zero and the position value is computed to keep the circle sprite in view at the edge.

I left the debugging information lines in but commented. If you use them, then comment lines 71 – 75.

Final work is to draw and this starts on line 164 where the canvas is cleared of all drawings.

Then lines 166 and 167 get our canvas background drawn.

The circle sprite is drawn on lines 169 and 170.

            /* Compute drawing metrics and draw frame */    
            function draw() 
            {
                // Increase velocity by acceleration
                vx += ax;
                vy += ay;
                // Update circle drawing position.
                x += vx;
                y += vy;
                /* Boundaries testing */
                // Right boundary
                if ( x + RADIUS > WIDTH  )
                {
                    x = WIDTH - RADIUS ;
                    vx = 0;
                }
                // Left boundary
                if (x - RADIUS  <= 0)
                {
                    x = RADIUS   ;
                    vx = 0;
                }
                // Bottom boundary
                if (y +  RADIUS  > HEIGHT)
                {
                    y = HEIGHT - RADIUS ;
                    vy = 0;
                }
                // Top boundary
                if (y - RADIUS  <= 0)
                {
                    y = RADIUS  ;
                    vy = 0;
                }
                
                // Debugging info.
                //console_log.innerHTML = 
                //'x: ' + x + '
' + //'y: ' + y + '
' + //'vx: ' + vx + '
' + //'vy: ' + vy + '
' + //'ax: ' + ax + '
' + //'ay: ' + ay + '
' ; /* Draw frame */ // Clear canvas clear(); // Draw canvas background canvas_ctx.fillStyle = CANVAS_COLOR; rect( 0, 0, WIDTH, HEIGHT ); /* Draw circle */ canvas_ctx.fillStyle = CIRCLE_COLOR; circle( x, y, RADIUS ); }

Good luck!



PhoneGap Cordova Camera XCode Example


This is a bare bones example of using Cordova or Phonegap to take a photo with your IPhone or IPad camera.

Learn cocos2D Game Development
PhoneGap Essentials: Building Cross-Platform Mobile Apps

The project uses XCode 4.3.2 and was tested using iOS 5.1 on a IPhone 4. There are no frills. I did make the button large enough for IPhone human guideline standards. I also added a simple console area to display debugging messages from the Javascript.

I also stripped out most of the extra Cordova comments that were not relevant.

Each time you take a picture another file is added. This example does not provide a way to delete the files. If you remove the app from the phone, the images are deleted. You may need to study the Cordova File API for how to manage your app’s local storage.

Here are the screens for the app.

The left screen is the app before any photo has been taken. It shows the integrated debugging console with the logged message that the Cordova onDeviceReady() method was called.

The middle screen is the IPhone Camera app with a photo just taken.

The right screen shows the app with a photo taken. You also see in the integrated console messages logged from the Javascript. The second line is the method called by touching the “Take Picture” button. The final message is the callback method from the Cordova getPicture camera method for a successful photo take. In particular you can see the file path and name of the photo.

Download XCode Project Files

Step 1 – Install Cordova for XCode

Instructions for setting up your development environment are located at the PhoneGap site Getting Started with iOS.

Step 2 – Create New Cordova-based Application

Step 3 – Set XCode Project Options


Set the XCode project options as follows:

  • Product name: Here I used CordovaCamera as the project name. You can use a name of your own choosing.
  • Company identifier: Provide your own reverse domain.
  • Use Automatic Reference Counting: Uncheck

Step 4 – Choose A File Location

Once you select a file location on your computer you will have a folder structure as follows:

And in XCode you will see a project window as follows:

You may notice the project has a warning. Ignore this for now.

Step 5 – Create and Add the www Folder and Files to the Project

These are the normal setup instructions for a Cordova alias PhoneGap XCode project. You can skip this step if you are used to creating Cordova XCode projects.

The process is creating a www folder by running the app once in the IPhone simulator and then add to the project explorer.

First run the app in the IPhone simulator.

The app runs but complains of the missing index.html file.

A www folder with this file and one other js file were created on your file system as this the app launched in the simulator. Here you see them and you need to drag the www folder into the Project Explorer. Do not drag to or copy to the XCode folders outside of XCode.

Fill out the “Choose options for adding these files” dialog as follows.

  • Destination: Unchecked
  • Folders: “Created folder references for added folders” selected.
  • Add to targets: CordovaCamera checked.

And this is the final results you see in the Project Explorer window.

Run the app in the IPhone simulator one more time.

This time you will be greeted with an Alert dialog with the “Cordova is working” message.

Step 7 – Code the index.html File

I removed code comments and commented code that is included in the index.html file.

Here is the full index.html file completed for your copy convenience.



  
  Camera
    
	
	
    
  
  
      

Cordova Camera


First look at the html starting on line 53. To simplify, the css is placed inline with tags versus the better approach of using an external css file.

  
      

Cordova Camera


Line 54 is the container div.

Line 55 provides a simple page heading.

Line 56 is the “Take Picture” button. It calls the capturePhoto() method when touched. Notice that you use the onClick handler, Cordova does the translation to touch up event for you.

Line 57 is the img tag for the photo once we take a picture.

Line 58 is a debugging div for output from your javascript. There are other debugging console solutions that may better serve your needs.

Back to the top of index.html, line 10 declares the console_log variable. It will globally reference the console_div div tag in the html. You can then see on lines 20 and 21 getting the reference from the DOM for console_div div tag.



  
  Camera
    
	
	
    



Tap, Move, Shake: Turning Your Game Ideas into iPhone & iPad Apps


Todd Moore’s new book, Tap, Move, Shake: Turning Your Game Ideas into iPhone & iPad Apps, is currently the best choice for getting started with writing and publishing IOS games.

A key feature is that the apps in the book are IN THE APP STORE. Never saw that trick before and I think is a standard for anyone writing IOS books. I actually followed the steps of creating an app I could download suffice it had a tad more flash in the store.

Tap, Move, Shake: Turning Your Game Ideas into iPhone & iPad Apps
Tap, Move, Shake: Turning Your Game Ideas into iPhone & iPad Apps

This is the first book I have seen in XCode/ObjectiveC that takes the submission to the App store as important a learning step as is the process of writing code. I loved the give and take App store rejection emails that provided a lot of insight for anyone who is going to submit an app the first time.

Also insightful is the special effort in giving the coder who is light on media creation great chapters on creating graphics and sound. Links provided are well researched.

On the wish list for me was not to dismiss ARC (Automatic Reference Counting) at the onset. Gee the book kinda assumes the beginner and ARC leans to that. But I suspect a case of examples completed at a time Apple was busy upsetting the cart for writers in progress.

The chapters are extremely well thought out especially the progression of development with the sections in each chapter.

I think you need a basic skill in XCode and Objective C to follow the book. XCode is introduced nicely for beginners and Objective C is learned more by example and less by explanation. I could not have solved some bugs without a basic skill in Objective C. The architecture of IOS app is explained well. I loved the clarity of explaining the bootstrap of an IOS app. I finally got it!

The book covers EVERYTHING you need from setting up for development, coding, basic testing, resource creation, app submission and even app marketing. All at a very clear to the point approach. The book examples make you feel you are starting at the beginning because they are from the gaming industry beginnings tuned to the phone.

This is 254 page book that has a good number of images taking up pages. Compared to 3 and 4 inch opus magnum IOS books out there that are OMGs difficult to hold open on the desk or in a lounge chair, Todd gets a great deal done as a focused writer. Cutting content is key. I rather buy more books than have big monsters.

Want to get started in IOS gaming without a gaming engine or better understand your gaming engine, then do this book.



XCode 4 IPhone Mountains of the USA Tutorial: Lesson 9 – Add Annotation to MapView


<== Lesson 8 || Overview ||

This lesson adds an annotation and pin on the map to better show the location of the mountain.

Detail View with MapView Annotation

MapAnnotation class is all that you need to get a pin on the map with an annotation above it.

However, you may want the annotation and pin to “drop in” or you might want to control the pin color. This requires a MKMapViewDelegate class and the viewForAnnotation method. In this method a MKPinAnnotationView object is created to embellish the annotation with more functionality as well as the “drop in” effect. The DetailViewController class will serve as the MKMapViewDelegate.

As you proceed through the steps, the code items not needed to “just show an annotation and pin” are identified for you so you can try an example without the special drop in effect. To summarize that approach in advance, you do not need to add the MKMapViewDelegate protocol to your DetailViewController.h file, you exclude the [mapView setDelegate:self]; line from the viewWillAppear method in the DetailViewContoller.m files and you will not need the viewForAnnotation method added in step 3.

Source Download

  1. Starting XCode 4 Project. This is the lesson 8 project completed.
  2. PHP and CSV Files. Script to read data file and selects by elevation and returns XML. See Lesson 2.
  3. Completed XCode 4 Project

Step 1: DetailViewController.h – Add the MKMapViewDelegate Protocol
Download and uncompress the Starting XCode Project file and open in XCode.

Open the DetailViewController.h class and add line 3 to include the MapAnnotation header.

On line 6 you need to edit in the MKMapViewDelegate protocol. This line is needed only if you want more functionality over the annotation such as pin color or a “drop in” effect by including the viewForAnnotation method.

#import 
#import 
#import "MapAnnotation.h"
#import "MountainItem.h"


@interface DetailViewController : UIViewController {
    MKMapView *mapView;
    
    MountainItem *mountainItem;
}

@property (nonatomic, retain) IBOutlet MKMapView *mapView;

@property (nonatomic, retain) MountainItem *mountainItem;

@end

Step 2: DetailViewController.m – Create the Annotation
Open the DetailViewController.m file.

The first 51 lines of code are not changing but included here for online reference:

#import "DetailViewController.h"


@implementation DetailViewController
@synthesize mapView;
@synthesize mountainItem;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [mapView dealloc];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.mapView = nil;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

Add the highlighed line in the next code view.

Line 68 sets this class to receive MKMapViewDelegate messages. In the last step you defined this class as MKMapViewDelegate.

Line 68 is not needed if all you want to show the annotation and pin without any special view or effects. A MKMapViewDelegate is not needed for that.

Line 70 clears all annotations from the map. You can leave this line out and the previous pins and their annotations will stay on the map. If you try some mountains in the same range or zoom way out, you will see the previous pins and when you touch the pin the annotation will appear.

Lines 71 to 73 create the annotation object, give it a title and position in the center of the view region created in the last lesson on lines 61 to 66.

The annotation is added to the map on line 75.

The annotation is selected on line 77. When you test the app, you should touch the annotation and the pin. You will see the selected and unselected state. Unselected, just a pin appears. Selected the title appears. Line 77 is achieving the selection process in code.

Line 78 is clean up.

-(void)viewWillAppear:(BOOL)animated 
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self setTitle:mountainItem.name];

    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
    region.center.latitude = [mountainItem.latitude doubleValue] ;
    region.center.longitude = [mountainItem.longitude doubleValue] ;
    region.span.longitudeDelta = 1.0f;
    region.span.latitudeDelta = 1.0f;
    [mapView setRegion:region animated:YES];
    
    [mapView setDelegate:self];
    
    [self.mapView removeAnnotations:self.mapView.annotations];
    MapAnnotation *ann = [[MapAnnotation alloc] init];
    ann.title = mountainItem.name;
    ann.coordinate = region.center;
    
    [mapView addAnnotation:ann];
    
    [mapView selectAnnotation:ann animated:YES];  
    [ann release];
}

Step 3: DetailViewController.m – Add Annotation View and Drop In Effect

The viewForAnnotation method is called to develop the view for an annotation.

This implementation is simple because we only have one annotation. The method is called for all annotations. With multiple annotation, you may need to treat certain annotations differently, so you might need to identify which is calling this method. As well if you are using a unpredictable number of annotations and some annotations persist, this is a place to determine how to reuse MKPinAnnotationView objects. All of this is beyond the scope of the tutorial, but this explains why you will see more lines of code in other examples and why this example appears simpler.

Line 83 creates the MKPinAnnotationView annView object. You are going to reuse the same MKPinAnnotationView, so the identifier MyPin is created to help that happen.

The pin “drop in” effect occurs because of line 84.

Line 85 is needed to show the pin annotation title. There are more items that can be added to the annotation such as a subtitle and left and right views.

The pin color is set on line 87. You can use MKPinAnnotationColorGreen and MKPinAnnotationColorPurple. These and MKPinAnnotationColorRed were added in IOS 3.0.

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id ) annotation

{
    MKPinAnnotationView *annView = [[[MKPinAnnotationView alloc ] initWithAnnotation:annotation reuseIdentifier:@"MyPin"] autorelease] ;
    annView.animatesDrop=TRUE;
    annView.canShowCallout = YES;
      
	annView.pinColor = MKPinAnnotationColorRed;
    
    return annView;
}

Try in the simulator. Tap the annotations and the pins to get the feel for them.



Register For Updates
You can opt out at anytime
* indicates required





XCode 4 IPhone Mountains of the USA Tutorial: Lesson 8 – Add MapView


<== Lesson 7 || Overview || Lesson 9 ==>

Now you have the second view added in the last lesson, you can add a map to show where the mountain is located. You can use the longitude and latitude that are part of the MountainItem data passed to the second view.

Detail View Screen with MapView

To work with a map, you need to include the MapKit framework. There are frameworks included automatically with a new IOS XCode project. They are UIKit, Foundation and CoreGraphics. You have probably noticed the import statement for UIKit in the header for MainViewController and DetailViewController.

In XCode 4 a group called Frameworks contains the frameworks you include with your project.

Typical Frameworks Group

It is a good practice to assure any new ones you add are in that group for easy reference.

Source Download

  1. Starting XCode 4 Project. This is the lesson 7 project completed.
  2. PHP and CSV Files. Script to read data file and selects by elevation and returns XML. See Lesson 2.
  3. Completed XCode 4 Project

Step 1: Add the MapKit Framework
Download and uncompress the Starting XCode Project file and open in XCode.

In the project explorer select the top node.

Select Project Node

In the center of XCode follow these steps:

Steps to Open Frameworks and Libraries Dialog

Type map into the search text field and you should see the list narrow down to the MapKit.framework choice and then select the Add button.

Frameworks and Libraries Dialog

Locate the MapKit.framework file in the project explorer and drag it into the Frameworks group. You could leave MapKit.framework where it was grouped, but keeping the frameworks together makes sense.

Drag MapKit Framework To Frameworks Group

Step 2: DetailViewController.h – Replace TextView with MapView

Open the DetailViewController.h file in the project explorer.

You are going to replace the UITextView with a MKMapView. Lines that are being replaced are included here for convenience.

#import 
#import "MountainItem.h"

@interface DetailViewController : UIViewController {
    UITextView *mountainInfoTextView;
    
    MountainItem *mountainItem;
}
@property (nonatomic, retain) IBOutlet UITextView *mountainInfoTextView;

@property (nonatomic, retain) MountainItem *mountainItem;
@end

Line 2 below show the inclusion of MapKit in this class.

Lines 6 and 11 give you an IBOutlet to the MapView you add later to the DetailViewController.xib.

#import 
#import 
#import "MountainItem.h"


@interface DetailViewController : UIViewController {
    MKMapView *mapView;
    
    MountainItem *mountainItem;
}

@property (nonatomic, retain) IBOutlet MKMapView *mapView;

@property (nonatomic, retain) MountainItem *mountainItem;

@end

Step 3: DetailViewController.m – Add mapView Property to the Implementation

Open the DetailViewController.m file in the project explorer.

These are the standard lines to include the mapView property to the implementation file.

You need to remove the mountainInfoTextView property and for convenience the lines are shown here.

#import "DetailViewController.h"


@implementation DetailViewController
@synthesize mountainInfoTextView;
@synthesize mountainItem;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [mountainInfoTextView dealloc];
    [mountainItem dealloc];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.mountainInfoTextView = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

Include the lines below to add the mapView object.

#import "DetailViewController.h"


@implementation DetailViewController
@synthesize mapView;
@synthesize mountainItem;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [mapView dealloc];
    [mountainItem dealloc];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.mapView = nil;
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


Step 4: DetailViewController.m – Show the Mountain’s Location on the Map

Remove line 58 because you are replacing the mountainInfoTextView with the coding for the mapView.

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setTitle:mountainItem.name];
     
    mountainInfoTextView.text = [NSString stringWithFormat: @"Name: %@\nElevation: %f\nLatitude: %f\nLongitude: %f",mountainItem.name, [mountainItem.elevation floatValue],  [mountainItem.latitude floatValue], [mountainItem.longitude floatValue]]; 

}
@end

Add the highlighted lines in the next code view.

The standard map type is set on line 59. You could also use MKMapTypeSatellite and MKMapTypeHybrid if you want to experiment.

Lines 60 and 61 are self explanatory.

The zoom and center point of the map is done on lines 62 to 67. Then center point is the longitude and latitude data passed into the class in the mountainItem object.

The span is an offset for the zoom. You can experiment with positive float numbers such as .01 which will zoom in tight. Because many of the mountains do not have any feature in standard map view, the value of 1 seems to show enough map details to keep from being disoriented.

-(void)viewWillAppear:(BOOL)animated 
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self setTitle:mountainItem.name];

    [mapView setMapType:MKMapTypeStandard];
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } };
    region.center.latitude = [mountainItem.latitude doubleValue] ;
    region.center.longitude = [mountainItem.longitude doubleValue] ;
    region.span.longitudeDelta = 1.0f;
    region.span.latitudeDelta = 1.0f;
    [mapView setRegion:region animated:YES];
    
}


@end

Step 5: DetailViewController.xib – Replace the TextView with the MapView

Open the DetailViewController.xib.

Delete the TextView in the design window.

Delete TextView

Drag the MapView from the Objects panel to the view in the design window and fill the view.

Drag MapView

With the MapView still selected open the Connections Inspector and drag a “New Referencing Outlet” to the File’s Owner and when you release the mouse select mapView, the name your are using in our DetailViewController to control the MapView. The Connections Inspector should look as follows:

Connections Inspector For MapView

Then finally as a double check select the File’s Owner and the Connections Inspector should appear as follows:

Connections Inspector for File's Owner

You should be good to check this out in the Simulator. Remember you need to hold down the Option button and drag the mouse to get the multi touch over the map for zooming. Scroll the map by dragging the mouse.

<== Lesson 7 || Overview || Lesson 9 ==>



Register For Updates
You can opt out at anytime
* indicates required