iOS 應用可以透過 Core Location 框架取得設備的地理位置。使用步驟是:添加 CoreLocation.framework 框架,導入 #import <CoreLocation/CoreLocation.h>。由於地圖與定位服務會消耗較多電量,一旦取到位置就應及時停止定位以節省電力。
核心在於實現 CLLocationManagerDelegate 的 didUpdateLocations: 方法,從中取得經緯度、精度、海拔與時間戳,並可進一步做「位置反編碼」(把座標翻譯成地址)。
- (void)createGPSMap {
self.locationManage = [[CLLocationManager alloc] init];
_locationManage.distanceFilter = kCLDistanceFilterNone; // 返回全部信息
_locationManage.desiredAccuracy = kCLLocationAccuracyBest; // 最高精度
_locationManage.delegate = self;
[_locationManage startUpdatingLocation]; // 開始定位
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
CLLocation *newLocation = [locations lastObject];
[_locationManage stopUpdatingLocation]; // 取到位置後立即停止定位
// 經緯度
CLLocationCoordinate2D coord2D = newLocation.coordinate;
NSLog(@"緯度 = %f 經度 = %f", coord2D.latitude, coord2D.longitude);
// 位置反編碼:把座標翻譯為地址信息
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *place in placemarks) {
NSLog(@"國家 = %@", place.country);
NSLog(@"市 = %@", place.locality);
NSLog(@"區 = %@", place.subLocality);
NSLog(@"街道 = %@", place.thoroughfare);
}
}];
}
運行結果示例(以經度 116.4、緯度 39.3 為例):

反過來,若要根據「地址字符串」查詢座標(即「地理編碼」),使用 geocodeAddressString: 即可:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:_locationTextField.text completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *placemark in placemarks) {
CLLocationCoordinate2D coordinate = placemark.location.coordinate;
NSLog(@"緯度 = %3.5f 經度 = %3.5f", coordinate.latitude, coordinate.longitude);
}
}];
取得位置後,可透過 MapKit 框架展示地圖。導入 #import <MapKit/MapKit.h>,並讓控制器遵循 MKMapViewDelegate 協議。以下為地圖初始化與自定義標注的核心代碼:
- (void)viewDidLoad {
[super viewDidLoad];
self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
self.mapView.showsUserLocation = YES; // 顯示用戶當前位置
self.mapView.delegate = self;
self.mapView.mapType = MKMapTypeStandard; // 標準地圖(另有衛星、混合模式)
// 經緯度、顯示範圍與區域
CLLocationCoordinate2D coord2D = {39.910650, 116.47030};
MKCoordinateSpan span = {0.1, 0.1}; // 數值越大,範圍越大
MKCoordinateRegion region = {coord2D, span};
[self.mapView setRegion:region animated:YES];
// 添加自定義標注
HMTAnnotation *annotation = [[HMTAnnotation alloc] initWithCGLocation:coord2D];
annotation.title = @"自定義標注位置";
annotation.subtitle = @"子標題";
[self.mapView addAnnotation:annotation];
[self.view addSubview:self.mapView];
}
// 返回標注視圖(大頭針視圖),類似自定義 UITableViewCell 的復用思路
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
static NSString *identifier = @"annotation";
MKPinAnnotationView *annotationView =
(MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
if (annotationView == nil) {
annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
}
if ([annotation isKindOfClass:[HMTAnnotation class]]) {
annotationView.pinColor = MKPinAnnotationColorGreen; // 大頭針顏色
annotationView.canShowCallout = YES; // 點擊是否顯示標題氣泡
annotationView.animatesDrop = YES; // 從天而降的動畫
// 標題氣泡右側的附屬按鈕
UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[button addTarget:self action:@selector(didClickAnnotationViewRightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
annotationView.rightCalloutAccessoryView = button;
annotationView.annotation = annotation;
return annotationView;
}
// 當前設備位置的標注返回 nil,系統會創建默認標注視圖
return nil;
}
自定義標注模型需遵循 MKAnnotation 協議,千萬別忘了引入:
#import <MapKit/MapKit.h>
@interface HMTAnnotation : NSObject <MKAnnotation>
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate; // 座標
@property (nonatomic, copy) NSString *title; // 位置名稱
@property (nonatomic, copy) NSString *subtitle; // 子信息(可選)
- (id)initWithCGLocation:(CLLocationCoordinate2D)coordinate;
@end
@implementation HMTAnnotation
- (id)initWithCGLocation:(CLLocationCoordinate2D)coordinate {
if (self = [super init]) {
_coordinate = coordinate;
}
return self;
}
@end
此外,MKMapViewDelegate 還提供了 didUpdateUserLocation:(位置更新)、didSelectAnnotationView:(選中標注)、regionDidChangeAnimated:(地圖區域變化)等多個回調,可根據需求進一步擴展。若需要完全自定義錨點樣式,可考慮改用 MKAnnotationView(MKPinAnnotationView 只能以大頭針形式顯示)。
運行效果如下:
