Building Location-Based Applications for the iPhone : Page 3

Knowing where a device is opens the door to all kinds of innovative applications—and the iPhone's Core Location framework makes discovering location simple.

by Wei-Meng Lee

Sep 29, 2009

Page 3 of 3

Displaying Maps

While obtaining the location coordinates of a position is interesting, such information is much more useful if you can visually locate it on a map. Fortunately, the iPhone SDK 3.0 ships with the Map Kit API, which makes displaying Google Maps in your application a snap. Here's an example.

Using the same project you created in the previous section, add a Button view to the View window in the LBSViewController.xib file (see Figure 3).

Creates an instance of the MKMapView class when the view has loaded, and sets the map type (hybrid: map and satellite in this case) to display.

Adds the mapView object to the current view when a user taps the View Map button.

Zooms into the location using the mapView object's setRegion: method whenever the location information gets updated.

Press Command-r to test the application on the iPhone Simulator. Now, tapping on the View Map button will show a map containing the location reported by the location manager (see Figure 4).

Because the simulator always provides the same fixed location, this is as far as you can go without testing on a real device. When you do that, you'll be able to see the map update itself dynamically as you move the device around. Be sure to alter the distanceFilter property to a smaller number so that you will be able to track small changes in distance.

As you've seen, the iPhone SDK's Core Location framework makes it easy to implement location-based services. In addition, the MapKit (also in the iPhone 3.0 SDK) makes displaying maps a snap. If you have not yet had an opportunity to build a location-based application, you're coming to the field at the right time. With all these new features, now is the perfect time to begin!

Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.