您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS MapKit 地圖使用:顯示地圖、定位與反地理編碼

編輯:iOS 開發綜合

MapKit 是 iOS 內建的地圖框架,可以顯示標準地圖、衛星地圖與混合地圖,也能搭配 CoreLocation 顯示使用者位置,並透過 CLGeocoder 做地址反向解析。

引入 MapKit

#import <MapKit/MapKit.h>

建立 MKMapView

MKMapView *mapView =
    [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];

mapView.delegate = self;
mapView.showsUserLocation = YES;
mapView.mapType = MKMapTypeStandard;

CLLocationCoordinate2D coordinate = {33.00, 112.52};
MKCoordinateSpan span = {5, 5};
MKCoordinateRegion region = {coordinate, span};

[mapView setRegion:region];
[self.view addSubview:mapView];

啟動定位

self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];

反地理編碼

取得座標後,可以使用 CLGeocoder 把經緯度轉為地址資訊。

self.geocoder = [[CLGeocoder alloc] init];

[self.geocoder reverseGeocodeLocation:newLocation
                    completionHandler:^(NSArray *placemarks, NSError *error) {
    for (CLPlacemark *place in placemarks) {
        NSLog(@"name: %@", place.name);
        NSLog(@"country: %@", place.country);
        NSLog(@"locality: %@", place.locality);
    }
}];

常見問題

執行時若看到 CGBitmapContextCreate: unsupported parameter combination 或 vImage decode failed 的訊息,通常與地圖渲染或圖片資源的位圖設定有關。若地圖仍能顯示,可先確認是否來自特定模擬器、圖片資產或第三方圖層。

MapKit 的基本流程是:建立地圖視圖、設定代理、啟動定位、接收位置更新,最後依需求顯示標註或進行地址解析。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved