マーカーが配置された地図を追加する

このチュートリアルでは、マーカーが配置されたシンプルな Google マップを iOS アプリに追加する方法を説明します。Xcode の一般的な知識に加えて、Swift または Objective-C について初級から中級の知識がある方に適しています。地図の作成に関する高度なガイドについては、デベロッパー ガイドをご覧ください。

このチュートリアルでは、次の地図を作成します。マーカーの位置は、オーストラリアのシドニーです。

シドニーにマーカーが配置された地図を示したスクリーンショット

コードを取得する

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

Maps SDK for iOS は、Swift Package Manager を使用してインストールできます。

  1. 既存の Maps SDK for iOS の依存関係がすべて削除されていることを確認します。
  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. [File] > [Add Package Dependencies] に移動します。
  6. URL として「https://github.com/googlemaps/ios-maps-sdk」と入力し、Enter キーを押してパッケージを取得し、[Add Package] をクリックします。
  7. [File] > [Packages] > [Reset Package Cache] に移動して、パッケージ キャッシュのリセットが必要になる場合があります。

CocoaPods を使用

  1. Xcode バージョン 15.0 以降をダウンロードしてインストールします。
  2. CocoaPods をまだインストールしていない場合は、ターミナルから次のコマンドを実行して macOS に CocoaPods をインストールします。
    sudo gem install cocoapods
  3. tutorials/map-with-marker ディレクトリに移動します。
  4. pod install コマンドを実行します。これにより、Podfile で指定した Maps SDK が依存関係とともにインストールされます。
  5. pod outdated を実行して、インストールされた Pod のバージョンと新しいアップデートを比較します。新しいバージョンが検出された場合は、pod update を実行して Podfile を更新し、最新の SDK をインストールします。詳しくは、CocoaPods ガイドをご覧ください。
  6. プロジェクトの map-with-marker.xcworkspace ファイルを(ダブルクリックして)Xcode で開きます。プロジェクトを開くには、.xcworkspace ファイルを使用する必要があります。

API キーを取得して必要な API を有効にする

このチュートリアルを完了するには、Maps SDK for iOS の使用が許可されている Google API キーが必要です。次のボタンをクリックしてキーを取得し、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 キーを取得してアプリに追加しているかご確認ください。Xcode のデバッグ コンソールで、API キーに関するエラー メッセージを確認します。
  • API キーを iOS バンドル ID で制限している場合は、そのキーを編集してアプリのバンドル ID(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;
          

デフォルトでは、Maps SDK for iOS はユーザーがマーカーをタップすると、情報ウィンドウにコンテンツが表示されます。このデフォルト動作で問題ない場合は、マーカーのクリック リスナーを追加する必要はありません。

お疲れさまでした。特定の場所を示すマーカーが配置された Google マップを表示する iOS アプリが作成されました。また、 Maps SDK for iOS の使用方法も確認しました。

次のステップ

地図オブジェクトと、マーカーを使ってできることについて、詳しく確認します。