標籤:ios mkmapview嵌入地圖
要看到那個google的地圖,在實現上也相當簡便。嵌入地圖時需要MKMapView這個類,它有很多方法和屬性,不過如果只是想得到基本的定位功能的話,只需執行個體化一個對像然後加到當前的view上就可以了。<一>先介紹一下,它的幾個常用的屬性。 region 用來設定地圖的那一部份被顯示,它是一個結構體,定義如下: typedef struct{ CLLocationCoordinate2D center;//表示顯示的中心 MKCoordinateSpan span; //表示比例}MKCoordinateRegion;對於MKCoordinateSpan其定義如下:typedef struct{CLLocationDegrees latitudeDelta;//這類型在前一節中講過了,是double型的CLLocationDegrees longitudeDlta;}MKCoordinateSpan;再看一下maptype屬性,它用於設定地圖的類型,如下所示: MapType屬性值 描述 MKMapTypeStandard 表示標準的街道級地圖 MKMapTypeSatellite 表示衛星圖 MKMapTypeHybird 表示上面兩者的混合其餘的就不再一一介紹了,去看看相關的文檔即可,在這裡已經可以把地圖弄出來了。<二>下面我們把上一節中的代碼改一下: .h標頭檔#import <UIKit/UIKit.h>#import <CoreLocation/CoreLocation.h>#import <MapKit/MapKit.h>@interface CoreLocationViewController : UIViewController<CLLocationManagerDelegate,MKMapViewDelegate>{ MKMapView *map; CLLocationManager *locManager; CLLocationCoordinate2D loc;}@property (nonatomic, retain) MKMapView *map;@property (nonatomic, retain) CLLocationManager *locManager;- (void)setCurrentLocation:(CLLocation *)location;@end .m源檔案#import "CoreLocationViewController.h"@implementation CoreLocationViewController@synthesize map;@synthesize locManager;- (void)viewDidLoad { map = [[MKMapView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 411.0f)]; map.showsUserLocation = YES; [self.view addSubview:map]; locManager = [[CLLocationManager alloc] init]; locManager.delegate = self; locManager.desiredAccuracy = kCLLocationAccuracyBest; locManager.distanceFilter = 100; [locManager startUpdatingLocation]; [super viewDidLoad];} - (void)dealloc { [map release]; [locManager release]; [super dealloc];}#pragma mark -#pragma mark Core Location Delegate Methods- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"---------------"); loc = [newLocation coordinate]; MKCoordinateRegion region; MKCoordinateSpan span; span.latitudeDelta=0.1; //zoom level span.longitudeDelta=0.1; //zoom level NSLog(@"%f",loc.latitude); NSLog(@"%f",loc.longitude); region.span=span; region.center=loc; // map.showsUserLocation=NO; map.mapType = MKMapTypeStandard; [map setRegion:region animated:YES]; [map regionThatFits:region];}- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ NSString *errorMessage; if ([error code] == kCLErrorDenied){ errorMessage = @"被拒絕訪問"; } if ([error code] == kCLErrorLocationUnknown) { errorMessage = @""; } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:errorMessage delegate:self cancelButtonTitle:@"紜畾" otherButtonTitles:nil]; [alert show]; [alert release];}- (void)setCurrentLocation:(CLLocation *)location { MKCoordinateRegion region ; region.center = location.coordinate; region.span.longitudeDelta = 0.15f; region.span.latitudeDelta = 0.15f; [map setRegion:region animated:YES];}@end
iOS MKMapView嵌入地圖