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

iOS 地點搜尋與地圖標注:用 CLGeocoder 搭配 MKMapView 大頭針

編輯:iOS 開發綜合

讓使用者輸入一個地名,App 回應以地圖位置與大頭針標記——這是許多工具型 App 的基礎功能。實作上需要兩個互補的元件:CLGeocoder 負責把文字變成座標,MKMapView 負責把座標畫成視覺。

動手前記得先把 MapKit.framework 加入專案,並在需要定位時額外引入 CoreLocation.framework。

第一步:介面與 delegates

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import "mapLocation.h"

@interface chonViewController : UIViewController <MKMapViewDelegate>

@property (weak, nonatomic) IBOutlet UITextField *txtQueryKey;
@property (weak, nonatomic) IBOutlet MKMapView *mapView;

- (IBAction)geocodeQuery:(id)sender;

@end

第二步:初始化地圖

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 設定地圖類型為標準模式
    _mapView.mapType = MKMapTypeStandard;

    // 必須設定 delegate,否則 viewForAnnotation 不會被回呼
    _mapView.delegate = self;
}

漏掉 mapView.delegate = self 是最常見的失誤,會導致大頭針看得到卻沒有自訂樣式。

第三步:文字轉座標並落地標

#pragma mark - 查詢按鈕觸發動作

- (IBAction)geocodeQuery:(id)sender
{
    if (_txtQueryKey.text == nil || [_txtQueryKey.text length] == 0) {
        return;
    }

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:_txtQueryKey.text completionHandler:^(NSArray *placemarks, NSError *error) {
        NSLog(@"查詢結果筆數: %i", [placemarks count]);

        // 先清掉舊的標注,避免重複堆疊
        if ([placemarks count] > 0) {
            [_mapView removeAnnotations:_mapView.annotations];
        }

        for (int i = 0; i < [placemarks count]; i++) {
            CLPlacemark *placemark = placemarks[i];

            // 收起鍵盤
            [_txtQueryKey resignFirstResponder];

            // 調整地圖顯示區域:參數依序為中心座標、南北跨度、東西跨度(單位:公尺)
            MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(
                placemark.location.coordinate, 10000, 10000);
            [_mapView setRegion:viewRegion animated:YES];

            // 建立自訂標注物件
            mapLocation *annotation = [[mapLocation alloc] init];
            annotation.streetAddress = placemark.thoroughfare;
            annotation.city = placemark.locality;
            annotation.state = placemark.administrativeArea;
            annotation.zip = placemark.postalCode;
            annotation.coordinate = placemark.location.coordinate;

            // 加入標注後,系統會回呼 viewForAnnotation:
            [_mapView addAnnotation:annotation];
        }
    }];
}

第四步:自訂大頭針樣式

#pragma mark - MKMapViewDelegate

- (MKAnnotationView *)mapView:(MKMapView *)theMapView
            viewForAnnotation:(id<MKAnnotation>)annotation
{
    // 以 dequeue 方式複用,避免大量標注時配置過多物件
    MKPinAnnotationView *annotationView =
        (MKPinAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];

    if (annotationView == nil) {
        annotationView = [[MKPinAnnotationView alloc]
            initWithAnnotation:annotation reuseIdentifier:@"PIN_ANNOTATION"];
    }

    annotationView.pinColor = MKPinAnnotationColorPurple;  // 紫色大頭針
    annotationView.animatesDrop = YES;                     // 落下動畫
    annotationView.canShowCallout = YES;                   // 允許點擊彈出資訊

    return annotationView;
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    _mapView.centerCoordinate = userLocation.location.coordinate;
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)theMapView withError:(NSError *)error
{
    NSLog(@"error : %@", [error description]);
}

第五步:標注模型

任何要放到地圖上的自訂物件,都必須遵循 MKAnnotation 協定並實作 coordinate 屬性:

// mapLocation.h
#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface mapLocation : NSObject <MKAnnotation>

// 地理座標(MKAnnotation 的必備實作)
@property (nonatomic, readwrite) CLLocationCoordinate2D coordinate;

// 街道
@property (nonatomic, copy) NSString *streetAddress;
// 城市
@property (nonatomic, copy) NSString *city;
// 州/省
@property (nonatomic, copy) NSString *state;
// 郵遞區號
@property (nonatomic, copy) NSString *zip;

@end

title 與 subtitle 是可選實作,決定彈出氣泡裡顯示什麼。把地址資訊拼成人類可讀的形式,通常放在 subtitle:

// mapLocation.m
@implementation mapLocation

#pragma mark 標點主標題
- (NSString *)title
{
    return @"您的位置!";
}

#pragma mark 標點副標題
- (NSString *)subtitle
{
    NSMutableString *ret = [NSMutableString new];

    if (_state) {
        [ret appendString:_state];
    }
    if (_city) {
        [ret appendString:_city];
    }
    if (_city && _state) {
        [ret appendString:@", "];
    }
    if (_streetAddress && (_city || _state || _zip)) {
        [ret appendString:@" · "];
    }
    if (_streetAddress) {
        [ret appendString:_streetAddress];
    }
    if (_zip) {
        [ret appendFormat:@", %@", _zip];
    }

    return ret;
}

@end

幾個實務上的補充

使用者定位需要權限描述。若要用到 didUpdateUserLocation:,Info.plist 必須加上 NSLocationWhenInUseUsageDescription,並呼叫 requestWhenInUseAuthorization。缺少描述文字的話,iOS 8 之後會直接靜默失敗。

地理編碼有額度與錯誤碼。CLGeocoder 會被系統節流,回傳的 error 可能是 CLErrorGeocodeFoundNoResult 或 CLErrorNetwork,正式專案務必處理。此外大量批次查詢建議自行快取結果。

多筆結果的處理。範例中每筆結果都呼叫 setRegion:,多筆時畫面會不斷跳動。實務上通常只取第一筆,或改用 MKLocalSearch 搭配自訂的結果列表。

改用 MKLocalSearch。iOS 6.1 之後推薦 MKLocalSearch,它能一次取回多筆結果並提供 request/response 結構,比 CLGeocoder 更適合搜尋情境。

MapKit 與 SwiftUI/MapKit 新 API。若為新專案,可考慮 MKMapItem、MKMapSnapshotter,或在 SwiftUI 中直接使用 Map 元件與 Marker,能省下大量 delegate 樣板程式。

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