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

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

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

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

コードを取得する

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/mapwithmarker ディレクトリに移動します。
  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 キーを押してパッケージを取り込み、[パッケージを追加] をクリックします。
  7. [File] > [Packages] > [Reset Package Cache] を使用して、パッケージ キャッシュのリセットが必要になることがあります。

CocoaPods を使用

  1. Xcode バージョン 14.0 以降をダウンロードしてインストールします。
  2. CocoaPods をまだインストールしていない場合は、ターミナルから次のコマンドを実行して、macOS にインストールします。
    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. Xcode でプロジェクトの map-with-marker.xcworkspace ファイルを開く(ダブルクリック)プロジェクトを開くには、.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 の使用方法も確認しました。

次のステップ

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