마커가 포함된 지도 추가

이 튜토리얼에서는 마커가 있는 간단한 Google 지도를 iOS에 추가하는 방법을 보여줍니다. 있습니다. Swift 또는 Objective-C 및 Xcode에 대한 일반적인 지식 고급 가이드에서 지도를 만드는 방법에 대한 자세한 내용은 참조하세요.

이 튜토리얼을 사용하여 다음 지도를 만듭니다. 마커의 위치는 다음과 같습니다. 호주 시드니에요.

시드니 위에 마커가 표시된 지도를 보여주는 스크린샷

코드 가져오기

Google Cloud Storage에 GitHub의 Google 지도 iOS 샘플 저장소

또는 다음 버튼을 클릭하여 소스 코드를 다운로드하세요.

코드 받기

Swift

/*
 * Copyright 2020 Google Inc. All rights reserved.
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under
 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
 * ANY KIND, either express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

import UIKit
import GoogleMaps

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        // Create a GMSCameraPosition that tells the map to display the
        // coordinate -33.86,151.20 at zoom level 6.
        let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
        let mapView = GMSMapView.map(withFrame: self.view.frame, camera: camera)
        self.view.addSubview(mapView)

        // Creates a marker in the center of the map.
        let marker = GMSMarker()
        marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
        marker.title = "Sydney"
        marker.snippet = "Australia"
        marker.map = mapView
  }
}

      

Objective-C

/*
* Copyright 2020 Google Inc. All rights reserved.
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

#import "ViewController.h"
#import <GoogleMaps/GoogleMaps.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
  // Do any additional setup after loading the view.
  // Create a GMSCameraPosition that tells the map to display the
  // coordinate -33.86,151.20 at zoom level 6.
  GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                          longitude:151.20
                                                               zoom:6];
  GMSMapView *mapView = [GMSMapView mapWithFrame:self.view.frame camera:camera];
  mapView.myLocationEnabled = YES;
  [self.view addSubview:mapView];

  // Creates a marker in the center of the map.
  GMSMarker *marker = [[GMSMarker alloc] init];
  marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
  marker.title = @"Sydney";
  marker.snippet = @"Australia";
  marker.map = mapView;
}

@end

      

시작하기

Swift Package Manager

iOS용 Maps SDK는 Swift Package Manager를 사용하여 설치할 수 있습니다.

  1. 기존 iOS용 Maps SDK 종속 항목이 모두 삭제되었는지 확인합니다.
  2. 터미널 창을 열고 tutorials/map-with-marker 디렉터리로 이동합니다.
  3. Xcode 작업공간이 닫혀 있는지 확인하고 다음 명령어를 실행합니다.
    sudo gem install cocoapods-deintegrate cocoapods-clean
    pod deintegrate
    pod cache clean --all
    rm Podfile
    rm map-with-marker.xcworkspace
  4. Xcode 프로젝트를 열고 Podfile을 삭제합니다.
  5. 파일 > 패키지 종속 항목 추가를 참조하세요.
  6. URL에 https://github.com/googlemaps/ios-maps-sdk를 입력하고 Enter 키를 눌러 패키지를 가져온 다음 패키지 추가를 클릭합니다.
  7. 파일 > 패키지 > Package Cache 재설정을 참조하세요.

CocoaPods 사용

  1. Xcode 다운로드 및 설치 버전 15.0 이상
  2. 아직 CocoaPods가 없다면 터미널에서 다음 명령어를 실행하여 macOS에 설치합니다.
    sudo gem install cocoapods
  3. tutorials/map-with-marker 디렉터리로 이동합니다.
  4. pod install 명령어를 실행합니다. 이렇게 하면 Podfile에 지정된 Maps SDK가 모든 종속 항목과 함께 설치됩니다.
  5. pod outdated를 실행하여 설치된 포드 버전을 새 업데이트와 비교합니다. 새 버전이 감지되면 pod update를 실행하여 Podfile를 업데이트하고 최신 SDK를 설치합니다. 자세한 내용은 CocoaPods 가이드를 참고하세요.
  6. 프로젝트의 map-with-marker.xcworkspace를 엽니다 (더블클릭). Xcode에서 엽니다. .xcworkspace 파일을 사용하여 프로젝트를 열어야 합니다.

API 키 가져오기 및 필요한 API 사용 설정하기

이 가이드를 완료하려면 iOS용 Maps SDK를 사용합니다. 다음 버튼을 클릭하여 API를 활성화합니다

시작하기

자세한 내용은 API 키를 가져옵니다.

애플리케이션에 API 키 추가

다음과 같이 API 키를 AppDelegate.swift에 추가합니다.

  1. 다음 import 문이 파일에 추가되었습니다.
    import GoogleMaps
  2. application(_:didFinishLaunchingWithOptions:)에서 다음 줄을 수정합니다. 메서드에서 YOUR_API_KEY를 내 API 키로 대체합니다.
    GMSServices.provideAPIKey("YOUR_API_KEY")

앱 빌드 및 실행

  1. iOS 기기를 컴퓨터에 연결하거나 시뮬레이터 Xcode 스키마 메뉴에서 선택합니다.
  2. 기기를 사용 중인 경우 위치 서비스가 사용 설정되어 있는지 확인합니다. 시뮬레이터를 사용하는 경우 기능에서 위치를 선택합니다. 선택합니다.
  3. Xcode에서 Product/Run(제품/실행) 메뉴 옵션을 클릭합니다(또는 버튼 아이콘).
    • Xcode가 앱을 빌드한 다음 기기 또는 시뮬레이터에서 앱을 실행합니다.
    • 오스트레일리아 동쪽 해안의 시드니를 가리키는 마커가 포함된 지도가 표시됩니다. 이 페이지의 이미지와 비슷합니다.

문제 해결:

  • 지도가 표시되지 않으면 API 키를 가져와 앞에서 설명한 대로 앱에 전송합니다. 확인 API 키에 대한 오류 메시지를 위한 Xcode의 디버깅 콘솔
  • iOS 번들 식별자로 API 키를 제한한 경우 키를 사용하여 앱의 번들 식별자를 추가합니다. com.google.examples.map-with-marker
  • Wi-Fi 또는 GPS 연결 상태가 양호한지 확인합니다.
  • Xcode 디버깅 도구 사용 로그를 확인하고 앱을 디버그할 수 있습니다.

코드 이해하기

  1. 지도를 만들고 viewDidLoad()의 뷰로 설정합니다.

    Swift

    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
    let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
    view = mapView
          

    Objective-C

    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:-33.86
                                                            longitude:151.20
                                                                 zoom:6.0];
    GMSMapView *mapView = [[GMSMapView alloc] initWithFrame: CGRectZero camera:camera];
    self.view = mapView;
          
  2. viewDidLoad()의 지도에 마커를 추가합니다.

    Swift

    // Creates a marker in the center of the map.
    let marker = GMSMarker()
    marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
    marker.title = "Sydney"
    marker.snippet = "Australia"
    marker.map = mapView
          

    Objective-C

    // Creates a marker in the center of the map.
    GMSMarker *marker = [[GMSMarker alloc] init];
    marker.position = CLLocationCoordinate2DMake(-33.86, 151.20);
    marker.title = @"Sydney";
    marker.snippet = @"Australia";
    marker.map = mapView;
          

기본적으로 iOS용 Maps SDK는 을 표시합니다. 광고 항목의 클릭 리스너를 추가할 필요가 기본 동작으로 마음에 드는 경우 마커를 마커에 놓으세요.

수고하셨습니다. Google 지도를 표시하는 iOS 앱을 빌드했습니다. 아이콘을 사용하여 특정 위치를 나타냅니다. 또한 iOS용 Maps SDK를 사용하는 것이 좋습니다.

다음 단계

지도 객체마커로 수행할 수 있습니다.