지도를 길게 누르면 동작의 좌표가 역 지오코딩 서비스로 전송됩니다. 성공하면 결과가 포함된 정보 창이 있는 마커가 지도에 추가됩니다.
시작하기
샘플 코드를 사용하기 전에 개발 환경을 구성해야 합니다. 자세한 내용은 iOS용 Maps SDK 코드 샘플을 참고하세요.
코드 보기
Swift
import GoogleMaps import UIKit // Sample code for GeoCoder service. class GeocoderViewController: UIViewController { private lazy var mapView: GMSMapView = { let camera = GMSCameraPosition(latitude: -33.868, longitude: 151.2086, zoom: 12) return GMSMapView(frame: .zero, camera: camera) }() private lazy var geocoder = GMSGeocoder() override func loadView() { view = mapView mapView.delegate = self } } extension GeocoderViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) { // On a long press, reverse geocode this location. geocoder.reverseGeocodeCoordinate(coordinate) { response, error in guard let address = response?.firstResult() else { let errorMessage = error.map { String(describing: $0) } ?? "<no error>" print( "Could not reverse geocode point (\(coordinate.latitude), \(coordinate.longitude)): \(errorMessage)" ) return } print("Geocoder result: \(address)") let marker = GMSMarker(position: address.coordinate) marker.appearAnimation = .pop marker.map = mapView guard let lines = address.lines, let title = lines.first else { return } marker.title = title if lines.count > 1 { marker.snippet = lines[1] } } } }
Objective-C
#import "GoogleMapsDemos/Samples/GeocoderViewController.h" #import <GoogleMaps/GoogleMaps.h> @implementation GeocoderViewController { GMSMapView *_mapView; GMSGeocoder *_geocoder; } - (void)viewDidLoad { [super viewDidLoad]; GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.868 longitude:151.2086 zoom:12]; _mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera]; _mapView.delegate = self; _geocoder = [[GMSGeocoder alloc] init]; self.view = _mapView; } - (void)mapView:(GMSMapView *)mapView didLongPressAtCoordinate:(CLLocationCoordinate2D)coordinate { // On a long press, reverse geocode this location. __weak __typeof__(self) weakSelf = self; GMSReverseGeocodeCallback handler = ^(GMSReverseGeocodeResponse *response, NSError *error) { [weakSelf handleResponse:response coordinate:coordinate error:error]; }; [_geocoder reverseGeocodeCoordinate:coordinate completionHandler:handler]; } - (void)handleResponse:(nullable GMSReverseGeocodeResponse *)response coordinate:(CLLocationCoordinate2D)coordinate error:(nullable NSError *)error { GMSAddress *address = response.firstResult; if (address) { NSLog(@"Geocoder result: %@", address); GMSMarker *marker = [GMSMarker markerWithPosition:address.coordinate]; NSArray<NSString *> *lines = [address lines]; marker.title = [lines firstObject]; if (lines.count > 1) { marker.snippet = [lines objectAtIndex:1]; } marker.appearAnimation = kGMSMarkerAnimationPop; marker.map = _mapView; } else { NSLog(@"Could not reverse geocode point (%f,%f): %@", coordinate.latitude, coordinate.longitude, error); } } @end
전체 샘플 앱을 로컬에서 실행
iOS용 Maps SDK 샘플 앱은 GitHub에서 다운로드 보관 파일로 제공됩니다. 다음 단계에 따라 iOS용 Maps SDK 샘플 앱을 설치하고 사용해 보세요.
git clone https://github.com/googlemaps-samples/maps-sdk-for-ios-samples.git
를 실행하여 샘플 저장소를 로컬 디렉터리로 클론합니다.터미널 창을 열고 샘플 파일을 클론한 디렉터리로 이동한 후 GoogleMaps 디렉터리로 이동합니다.
Swift
cd maps-sdk-for-ios-samples-main/GoogleMaps-Swift
pod install
open GoogleMapsSwiftDemos.xcworkspace
Objective-C
cd maps-sdk-for-ios-samples-main/GoogleMaps
pod install
open GoogleMapsDemos.xcworkspace
- Xcode에서 컴파일 버튼을 눌러 현재 스키마로 앱을 빌드합니다. 빌드에서 오류가 발생하여 Swift의 경우
SDKConstants.swift
파일에, Objective-C의 경우SDKDemoAPIKey.h
파일에 API 키를 입력하라는 메시지가 표시됩니다. - iOS용 Maps SDK가 사용 설정된 프로젝트에서 API 키를 가져옵니다.
- Swift의 경우
SDKConstants.swift
파일, Objective-C의 경우SDKDemoAPIKey.h
파일을 수정하고apiKey
또는kAPIKey
상수 정의에 API 키를 붙여넣습니다. 예를 들면 다음과 같습니다.Swift
static let apiKey = "YOUR_API_KEY"
Objective-C
static NSString *const kAPIKey = @"YOUR_API_KEY";
SDKConstants.swift
파일 (Swift) 또는SDKDemoAPIKey.h
파일 (Objective-C)에서 다음 줄을 삭제합니다. 이 줄은 사용자 정의 문제를 등록하는 데 사용되기 때문입니다.Swift
#error (Register for API Key and insert here. Then delete this line.)
Objective-C
#error Register for API Key and insert here.
- 프로젝트를 빌드하고 실행합니다. iOS 시뮬레이터 창이 표시되고 Maps SDK 데모 목록이 표시됩니다.
- 표시된 옵션 중 하나를 선택하여 iOS용 Maps SDK의 기능을 실험해 보세요.
- GoogleMapsDemos에서 위치에 액세스하도록 허용하라는 메시지가 표시되면 허용을 선택합니다.