Menambahkan Peta dengan Penanda

Tutorial ini menunjukkan cara menambahkan peta Google sederhana beserta penanda ke iOS . Aplikasi ini cocok untuk pengguna yang memiliki pengetahuan pemula atau menengah tentang Swift atau Objective-C bersama dengan pengetahuan umum tentang Xcode. Untuk panduan lanjutan tentang membuat peta, baca panduan kami.

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

Screenshot yang menampilkan peta dengan penanda di atas Sydney

Mendapatkan kode

Clone atau download Repositori contoh iOS Google Maps di GitHub.

Atau, klik tombol berikut untuk mendownload kode sumber:

Beri saya kode

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

      

Mulai

Swift Package Manager

Maps SDK for iOS dapat diinstal menggunakan Swift Package Manager.

  1. Pastikan Anda telah menghapus semua dependensi Maps SDK for iOS yang ada.
  2. Buka jendela terminal dan buka direktori tutorials/map-with-marker.
  3. Pastikan ruang kerja Xcode Anda 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 Anda dan hapus podfile.
  5. Buka File > Tambahkan Dependensi Paket.
  6. Masukkan https://github.com/googlemaps/ios-maps-sdk sebagai URL, tekan Enter untuk menarik paket, lalu klik Add Package.
  7. Anda mungkin perlu menyetel ulang cache paket menggunakan File > Paket > Reset Cache Paket.

Menggunakan CocoaPods

  1. Download dan instal Xcode versi 15.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. Arahkan ke direktori tutorials/map-with-marker.
  4. Jalankan perintah pod install. 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) map-with-marker.xcworkspace proyek 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 membutuhkan kunci Google API yang telah diotorisasi untuk menggunakan Maps SDK for iOS. Klik tombol berikut untuk mendapatkan kunci, lalu mengaktifkan API.

Memulai

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 tersebut:
    import GoogleMaps
  2. Edit baris berikut di 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, atau pilih mesin pencuci piring dari menu skema Xcode.
  2. Jika Anda menggunakan perangkat, pastikan layanan lokasi diaktifkan. Jika Anda menggunakan simulator, pilih lokasi dari Fitur Google Spreadsheet.
  3. Di Xcode, klik opsi menu Product/Run (atau tombol Play ikon tombol).
    • Xcode akan membangun aplikasi, lalu menjalankan aplikasi tersebut di perangkat atau pada simulator.
    • Anda akan melihat peta dengan penanda yang berpusat di Sydney di pantai timur Australia, sama seperti gambar di halaman ini.

Pemecahan masalah:

  • Jika peta tidak muncul, pastikan Anda telah mendapatkan kunci API dan menambahkan ke aplikasi, seperti yang dijelaskan sebelumnya. Periksa Konsol proses debug Xcode untuk pesan error tentang kunci API.
  • Jika Anda telah membatasi kunci API oleh ID paket iOS, edit untuk menambahkan ID paket bagi aplikasi: com.google.examples.map-with-marker.
  • Pastikan Anda memiliki koneksi Wi-Fi atau GPS yang baik.
  • Menggunakan alat debug Xcode untuk melihat log dan men-debug 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 info saat pengguna mengetuk penanda. Tidak perlu menambahkan pemroses klik untuk penanda jika Anda puas menggunakan perilaku default.

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

Langkah berikutnya

Pelajari lebih lanjut objek peta dan hal yang ingin Anda dapat dilakukan dengan penanda.