技术开发 频道

实战iPhone应用开发之:GPS定位系统

  显示地图

  如果能将位置坐标定位到地图上显示将会更有趣,幸运的是,iPhone 3.0 SDK包括了Map Kit API,它可以让你在程序中显示Google Map,下面以一个例子进行说明。

  还是使用前面创建的项目,在LBSViewController.xib文件中视图窗口上增加一个按钮,如图3所示。

  图 3 View Map按钮:增加按钮后的样子

  在Xcode中框架组上点击右键,增加一个新的框架MapKit.framework。在LBSViewController.h文件中添加下列代码中的粗体部分:

#import <UIKit/UIKit.h>
#import
<CoreLocation/CoreLocation.h>
#import
<MapKit/MapKit.h>
@interface LBSViewController : UIViewController
    
<CLLocationManagerDelegate> {
    IBOutlet UITextField
*accuracyTextField;
    IBOutlet UITextField
*latitudeTextField;
    IBOutlet UITextField
*longitudeTextField;
    CLLocationManager
*lm;
  
    MKMapView
*mapView;
}
@property (retain, nonatomic) UITextField
*accuracyTextField;
@property (retain, nonatomic) UITextField
*latitudeTextField;
@property (retain, nonatomic) UITextField
*longitudeTextField;

-(IBAction) btnViewMap: (id) sender;

@end

  回到界面编辑器,拖动按钮到文件的所有者项目上,然后选择btnViewMap:。

  在LBSViewController.m文件中,添加下列代码中的粗体部分:

-(IBAction) btnViewMap: (id) sender {
    [self.view addSubview:mapView];
}
- (void) viewDidLoad {
    lm
= [[CLLocationManager alloc] init];
    lm.
delegate = self;
    lm.desiredAccuracy
= kCLLocationAccuracyBest;
    lm.distanceFilter
= 1000.0f;
    [lm startUpdatingLocation];
    
    mapView
= [[MKMapView alloc] initWithFrame:self.view.bounds];
    mapView.mapType
= MKMapTypeHybrid;
}
- (void) locationManager: (CLLocationManager *) manager
    didUpdateToLocation: (CLLocation
*) newLocation
    fromLocation: (CLLocation
*) oldLocation{
    NSString
*lat = [[NSString alloc] initWithFormat:@"%g",
        newLocation.coordinate.latitude];
    latitudeTextField.text
= lat;
    
    NSString
*lng = [[NSString alloc] initWithFormat:@"%g",
        newLocation.coordinate.longitude];
    longitudeTextField.text
= lng;
    
    NSString
*acc = [[NSString alloc] initWithFormat:@"%g",
        newLocation.horizontalAccuracy];
    accuracyTextField.text
= acc;    
    
    [acc release];
    [lat release];
    [lng release];
    
    MKCoordinateSpan span;
    span.latitudeDelta
=.005;
    span.longitudeDelta
=.005;
    
    MKCoordinateRegion region;
    region.center
= newLocation.coordinate;
    region.span
=span;
    
    [mapView setRegion:region animated:TRUE];
}
- (void) dealloc{
    [mapView release];
    [lm release];
    [latitudeTextField release];
    [longitudeTextField release];
    [accuracyTextField release];
    [super dealloc];
}

  代码解释:

  l 当视图载入时创建一个MKMapView类的实例,设置显示的地图类型。

  l 当用户点击View Map按钮时,在当前视图上增加mapView对象。

  l 当位置信息得到更新时,使用mapView对象的setRegion:方法放大地图。

  在iPhone模拟器中按Command-r测试该程序,点击View Map按钮将会显示一个包含位置管理器返回位置的地图。如图4所示。

  图 4 地图位置:通过定位内核框架显示地图位置

  因为模拟器始终显示的是相同的位置,如果你有一部iPhone手机也可以真实地感受一下,当你移动位置时,你会看到地图会自动更新。将distanceFilter属性设置得小一点,这样可以增强跟踪体验。

  正如你所看到的,iPhone SDK的定位内核框架让你可以很容易实现基于位置的设备,此外,MapKit(包括在iPhone SDK中)可以在地图上显示位置信息。如果没有创建过基于位置的应用,我想你看完本文就应该动手一试,还等什么呢?

0
相关文章