Menambahkan Peta dengan Penanda

Tutorial ini menunjukkan cara menambahkan peta Google sederhana dengan penanda ke aplikasi iOS Anda. Tutorial ini cocok untuk orang yang memiliki pengetahuan tingkat pemula atau menengah tentang Swift atau Objective-C, serta pengetahuan umum tentang Xcode. Untuk panduan tingkat lanjut cara membuat peta, baca panduan developer.

Anda akan membuat peta berikut menggunakan tutorial ini. Penanda diposisikan di Sydney, Australia.

Screenshot yang menampilkan peta dengan penanda di atas Sydney

Mendapatkan kode

Clone atau download repositori contoh Google Maps untuk iOS di GitHub.

Atau, klik tombol berikut untuk mendownload kode sumber:

Beri saya kodenya

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

      

Memulai

Swift Package Manager

Maps SDK for iOS dapat diinstal menggunakan Swift Package Manager.

  1. Pastikan Anda telah menghapus dependensi Maps SDK for iOS yang ada.
  2. Buka jendela terminal dan buka direktori tutorials/mapwithmarker.
  3. Pastikan ruang kerja Xcode Anda sudah ditutup dan jalankan perintah berikut:
    sudo gem install cocoapods-deintegrate cocoapods-clean
    pod deintegrate
    pod cache clean --all
    rm Podfile
    rm map-with-marker.xcworkspace
  4. Buka project Xcode dan hapus podfile.
  5. Buka File > Add Package Dependencies.
  6. Masukkan https://github.com/googlemaps/ios-maps-sdk sebagai URL, tekan Enter untuk menarik paket, lalu klik Tambahkan Paket.
  7. Anda mungkin perlu mereset cache paket menggunakan File > Packages > Reset Package Cache.

Menggunakan CocoaPods

  1. Download dan instal Xcode versi 14.0 atau yang lebih baru.
  2. Jika Anda belum memiliki CocoaPods, instal di macOS dengan menjalankan perintah berikut dari terminal:
    sudo gem install cocoapods
  3. Buka direktori tutorials/map-with-marker.
  4. Jalankan perintah pod install. Tindakan ini akan menginstal Maps SDK yang ditentukan di Podfile, beserta dependensi apa pun.
  5. Jalankan pod outdated untuk membandingkan versi pod yang terinstal dengan update baru. Jika versi baru terdeteksi, jalankan pod update untuk mengupdate Podfile dan menginstal SDK terbaru. Untuk mengetahui detail selengkapnya, lihat Panduan CocoaPods.
  6. Buka (klik dua kali) file map-with-marker.xcworkspace project untuk membukanya di Xcode. Anda harus menggunakan file .xcworkspace untuk membuka project.

Mendapatkan kunci API dan mengaktifkan API yang diperlukan

Untuk menyelesaikan tutorial ini, Anda memerlukan kunci Google API yang telah diberi otorisasi untuk menggunakan Maps SDK for iOS. Klik tombol berikut untuk mendapatkan kunci dan mengaktifkan API.

Mulai

Untuk detail selengkapnya, lihat Mendapatkan kunci API.

Menambahkan kunci API ke aplikasi

Tambahkan kunci API ke AppDelegate.swift sebagai berikut:

  1. Perhatikan bahwa pernyataan impor berikut telah ditambahkan ke file:
    import GoogleMaps
  2. Edit baris berikut di metode application(_:didFinishLaunchingWithOptions:) Anda, dengan mengganti YOUR_API_KEY dengan kunci API Anda:
    GMSServices.provideAPIKey("YOUR_API_KEY")

Membuat dan menjalankan aplikasi

  1. Hubungkan perangkat iOS ke komputer Anda, atau pilih simulator dari menu skema Xcode.
  2. Jika Anda menggunakan perangkat, pastikan layanan lokasi diaktifkan. Jika Anda menggunakan simulator, pilih lokasi dari menu Features.
  3. Di Xcode, klik opsi menu Product/Run (atau ikon tombol putar).
    • Xcode membuat aplikasi, lalu menjalankan aplikasi tersebut di perangkat atau di simulator.
    • Anda akan melihat peta dengan penanda yang berpusat di Sydney di pantai timur Australia, sama seperti gambar di halaman ini.

Pemecahan masalah:

  • Jika Anda tidak melihat peta, pastikan bahwa Anda telah mendapatkan kunci API dan menambahkannya ke aplikasi, seperti yang dijelaskan sebelumnya. Periksa konsol proses debug Xcode untuk melihat pesan error tentang kunci API.
  • Jika Anda telah membatasi kunci API menurut ID paket iOS, edit kunci ini agar dapat menambahkan ID paket tersebut untuk aplikasi: com.google.examples.map-with-marker.
  • Pastikan Anda memiliki koneksi Wi-Fi atau GPS yang baik.
  • Gunakan alat proses debug Xcode untuk melihat log dan melakukan debug pada aplikasi.

Memahami kode

  1. Buat peta dan tetapkan sebagai tampilan di 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. Tambahkan penanda ke peta di 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;
          

Secara default, Maps SDK for iOS menampilkan konten jendela info saat pengguna mengetuk penanda. Anda tidak perlu menambahkan pemroses klik untuk penanda jika sudah puas menggunakan perilaku default.

Selamat! Anda telah membuat aplikasi iOS yang menampilkan peta Google dengan penanda untuk menunjukkan lokasi tertentu. Anda juga telah mempelajari cara menggunakan Maps SDK for iOS.

Langkah berikutnya

Pelajari lebih lanjut objek peta, dan tindakan yang dapat Anda lakukan dengan penanda.